I am porting a C++ library to Java and I need a heap data structure. Is there a standard implementation or will I need to do it myself?
Min heap:
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
Max heap:
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return - Integer.compare(o1, o2);
}
});
PriorityQueue uses a heap. Based on the oracle documentation at https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html it seems likely that it is an implementation of a binary heap. I don't think there is an official implementation of a fibonacci or pairing heap, though I'd love to see either one of the two available.
In Java PriorityQueue can be used as a Heap.
Min Heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
Max Heap:
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
No as such there isn't but you can use Priority Queue as a Heap. Its officially told by Oracle to use Priority Queue as a Heap you can also refer to this link for further clarification.
PriorityQueue<Integer> MinHeap = new PriorityQueue<>();
PriorityQueue<Integer> MaxHeap = new PriorityQueue<>(Comparator.reverseOrder());
You can also consider TreeSet, which guarantees log(n) time for basic operations (add, remove, contains).
For Java 8, updating on an existing answer:
You can use Java Priority Queue as a Heap.
Min Heap: --> to keep the min element always on top, so you can access it in O(1).
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
Max Heap: --> to keep the max element always on top, the same order as above.
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
Which is the same as (Integer o1, Integer o2) -> (- Integer.compare(o1,o2))
as suggested from other answers.
And you can use:
add
--> to add element to the queue. O(log n)
remove
--> to get and remove the min/max. O(log n)
peek
--> to get, but not remove the min/max. O(1)