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?
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 minHeap = new PriorityQueue();
Max Heap: --> to keep the max element always on top, the same order as above.
PriorityQueue 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)