Implement a heap data structure in Java.

Prerequisite:

Introduction to Priority Queues using Binary Heaps

 
In the above post, we have introduced the heap data structure and covered heapify-up, push, heapify-down, and pop operations. In this post, Java implementation of Max Heap and Min Heap is discussed.

1. Max Heap implementation in Java

Following is Java implementation of max-heap data structure. We have tried to keep the implementation similar to the java.util.PriorityQueue class.

Download  Run Code

Output:
 
Priority queue size is 3
Priority queue contains 2
 
Emptying queue: 15 3 2
The queue is empty
 
Calling remove operation on an empty heap
java.lang.Exception: Index out of range(Heap underflow)
The element with the highest priority is null
 
Calling peek operation on an empty heap
java.lang.Exception: Index out of range (Heap underflow)
The element with the highest priority is null
 
Printing array: [45, 4, 5]
 
The element with the highest priority is 45
The element with the highest priority is 5

2. Min Heap implementation in Java

The min-heap implementation is very similar to the max-heap implementation discussed above. The highlighted portion in the following code marks its differences with max-heap implementation:

Download  Run Code

Output:
 
Priority queue size is 3
Priority queue contains 2
 
Emptying queue: 2 3 15
The queue is empty
 
Calling remove operation on an empty heap
java.lang.Exception: Index out of range(Heap underflow)
The element with the highest priority is null
 
Calling peek operation on an empty heap
java.lang.Exception: Index out of range (Heap underflow)
The element with the highest priority is null
 
Printing array: [4, 5, 45]
 
The element with the highest priority is 4
The element with the highest priority is 5

Following is the time complexity of implemented heap operations:

  1. add() and poll() takes O(log(n)) time.
  2. toArray() and contains() takes O(n) time.
  3. peek() and size() and isEmpty() takes O(1) time.

 
Also See:

Min Heap and Max Heap Implementation in C++

 
Exercise: Implement Heap in Java using ArrayList instead of a Vector.

 
References: https://en.wikipedia.org/wiki/Heap_(data_structure)