1

There are two constructors for PriorityQueue in Java.

PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); //for max heap

public PriorityQueue(Collection<? extends E> c) //for creating PQ from a list

I am assuming the second one will take linear time (by directly heapifying) rather than O(n log n) if we add each element one by one. But this only takes one parameter so we can only construct min heap in linear time.

For max heap, we can't construct the heap in linear time because there is no constructor which take two arguments - comparator and the list.

So this seems a bit inconsistent to me, is there a way to construct max heap in linear time in Java?

0 Answers0