I have to construct a max-heap out of an array (called nums
in the following code) and so I'm using java.util.PriorityQueue
.
My code looks like this:
PriorityQueue<Integer> pq = new PriorityQueue<>(nums.length, (a, b) -> b - a);
for (int i = 0; i < nums.length; i++) {
pq.offer(nums[i]);
}
I'm trying to find the time complexity (in terms of Big-O notation) of the above for
loop.
I understand that PriorityQueue
don't specify the details of the growth of underlying data structure. (And in worst-case it can be O(n)
when expanding the internal-array and copying all the elements over the newly allocated space).
But I assume that when I specify the initialCapacity
and don't add elements more than this initialCapacity
, then the worst case time complexity of the above loop should be O(n)
instead of O(nlog(n))
. I understand from here that building time of heap is O(n)
and nlog(n)
is a loose upper bound.
Am I correct, or am I missing something?
I just want to understand that if I configure my PriorityQueue
with initialCapacity
of n
and add n
elements in that priority-queue, what will be the time complexity of this building-heap process?
PS: I already saw this, but answers for this question just claim things without explanation and may be they are not so Java specific.
I also see that java.util.PriorityQueue
has a constructor that takes in a Collection
. What will be the time complexity of this constructor? Shouldn't it be O(n)
?