STL has this really useful function. Is there any equivalent to this in Java? I could write my custom implementation but it would be useful not to reinvent the wheel.
std::make_heap
makes a binary heap, which is used as a priority-queue and is called PriorityQueue in Java.
Correction : there isn't a standard binary-heap class in Java, but I suggested two in the comment below.
PriorityQueue has a special constructor that can "heapify" an exisisting ArrayList (or any Collection).
Example:
ArrayList<Integer> x = new ArrayList<>();
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(x); // O(N)
This operation copies input whereas make_heap
just reorders the array in-place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.