Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Heap in java?

Tags:

java

heap

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?

like image 379
user1796942 Avatar asked Jan 04 '13 21:01

user1796942


People also ask

Does Java have a heap class?

We use PriorityQueue class to implement Heaps in Java. By default Min Heap is implemented by this class. To implement Max Heap, we use Collections.

What is heap in Java?

The Java heap is the area of memory used to store objects instantiated by applications running on the JVM. When the JVM is started, heap memory is created and any objects in the heap can be shared between threads as long as the application is running.

Where is heap in Java?

In Java, a heap is a chunk of memory which is shared among all threads. In a heap, all class instances and the array is allocated. It is created when JVM starts-up.

Does Java have a max heap?

Max heap is a complete binary tree, wherein the value of a root node at every step is greater than or equal to value at the child node. Below is an implementation of Max Heap using library functions.


2 Answers

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(o2, o1) or - 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)

like image 132
Ahmed Hamdy Avatar answered Sep 27 '22 23:09

Ahmed Hamdy


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);     } }); 
like image 27
user2015398 Avatar answered Sep 28 '22 01:09

user2015398