For example, given a List of Integer List<Integer> list = Arrays.asList(5,4,5,2,2)
, how can I get a maxHeap
from this List in O(n)
time complexity?
The naive method:
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (Integer i : list) {
maxHeap.offer(i);
}
However, the time complexity is O(nlogn)
.
We can trigger the heapify method by using the following constructor:
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(list);
The time complexity is O(n)
. However, it forces me to use the natural order which is the minHeap.
My Question:
How can I construct a PriorityQueue by heapifying a Collection with custom Comparator?
Ref: Java doc of PriorityQueue
PS:
@user207421
Heapify algorithm can transform any unsorted array into a heap in O(n)
time, not O(nlogn)
. There are many articles about heapify, also in CLRS's Introduction to Algorithms Page 159, build a heap from any unsorted array is O(n)
. And heap is also not a sorted array. It's a complete tree with heap property which can be encoded in array.