Related Articles

# Min Heap in Java

• Difficulty Level : Medium
• Last Updated : 20 Jun, 2021

A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node.
Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.
Example of Min Heap:

```            5                      13
/      \               /       \
10        15           16         31
/                      /  \        /  \
30                     41    51    100   41```

How is Min Heap represented?
A Min Heap is a Complete Binary Tree. A Min heap is typically represented as an array. The root element will be at Arr. For any ith node, i.e., Arr[i]

• Arr[(i -1) / 2] returns its parent node.
• Arr[(2 * i) + 1] returns its left child node.
• Arr[(2 * i) + 2] returns its right child node.

Operations on Min Heap:

1. getMin(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).
2. extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing root.
3. insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If new key is larger than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

Below is the implementation of Min Heap in Java

## Java

 `// Java implementation of Min Heap``public` `class` `MinHeap {``    ``private` `int``[] Heap;``    ``private` `int` `size;``    ``private` `int` `maxsize;` `    ``private` `static` `final` `int` `FRONT = ``1``;` `    ``public` `MinHeap(``int` `maxsize)``    ``{``        ``this``.maxsize = maxsize;``        ``this``.size = ``0``;``        ``Heap = ``new` `int``[``this``.maxsize + ``1``];``        ``Heap[``0``] = Integer.MIN_VALUE;``    ``}` `    ``// Function to return the position of``    ``// the parent for the node currently``    ``// at pos``    ``private` `int` `parent(``int` `pos)``    ``{``        ``return` `pos / ``2``;``    ``}` `    ``// Function to return the position of the``    ``// left child for the node currently at pos``    ``private` `int` `leftChild(``int` `pos)``    ``{``        ``return` `(``2` `* pos);``    ``}` `    ``// Function to return the position of``    ``// the right child for the node currently``    ``// at pos``    ``private` `int` `rightChild(``int` `pos)``    ``{``        ``return` `(``2` `* pos) + ``1``;``    ``}` `    ``// Function that returns true if the passed``    ``// node is a leaf node``    ``private` `boolean` `isLeaf(``int` `pos)``    ``{``        ``if` `(pos >= (size / ``2``) && pos <= size) {``            ``return` `true``;``        ``}``        ``return` `false``;``    ``}` `    ``// Function to swap two nodes of the heap``    ``private` `void` `swap(``int` `fpos, ``int` `spos)``    ``{``        ``int` `tmp;``        ``tmp = Heap[fpos];``        ``Heap[fpos] = Heap[spos];``        ``Heap[spos] = tmp;``    ``}` `    ``// Function to heapify the node at pos``    ``private` `void` `minHeapify(``int` `pos)``    ``{` `        ``// If the node is a non-leaf node and greater``        ``// than any of its child``        ``if` `(!isLeaf(pos)) {``            ``if` `(Heap[pos] > Heap[leftChild(pos)]``                ``|| Heap[pos] > Heap[rightChild(pos)]) {` `                ``// Swap with the left child and heapify``                ``// the left child``                ``if` `(Heap[leftChild(pos)] < Heap[rightChild(pos)]) {``                    ``swap(pos, leftChild(pos));``                    ``minHeapify(leftChild(pos));``                ``}` `                ``// Swap with the right child and heapify``                ``// the right child``                ``else` `{``                    ``swap(pos, rightChild(pos));``                    ``minHeapify(rightChild(pos));``                ``}``            ``}``        ``}``    ``}` `    ``// Function to insert a node into the heap``    ``public` `void` `insert(``int` `element)``    ``{``        ``if` `(size >= maxsize) {``            ``return``;``        ``}``        ``Heap[++size] = element;``        ``int` `current = size;` `        ``while` `(Heap[current] < Heap[parent(current)]) {``            ``swap(current, parent(current));``            ``current = parent(current);``        ``}``    ``}` `    ``// Function to print the contents of the heap``    ``public` `void` `print()``    ``{``        ``for` `(``int` `i = ``1``; i <= size / ``2``; i++) {``            ``System.out.print(``" PARENT : "` `+ Heap[i]``                             ``+ ``" LEFT CHILD : "` `+ Heap[``2` `* i]``                             ``+ ``" RIGHT CHILD :"` `+ Heap[``2` `* i + ``1``]);``            ``System.out.println();``        ``}``    ``}` `    ``// Function to remove and return the minimum``    ``// element from the heap``    ``public` `int` `remove()``    ``{``        ``int` `popped = Heap[FRONT];``        ``Heap[FRONT] = Heap[size--];``        ``minHeapify(FRONT);``        ``return` `popped;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] arg)``    ``{``        ``System.out.println(``"The Min Heap is "``);``        ``MinHeap minHeap = ``new` `MinHeap(``15``);``        ``minHeap.insert(``5``);``        ``minHeap.insert(``3``);``        ``minHeap.insert(``17``);``        ``minHeap.insert(``10``);``        ``minHeap.insert(``84``);``        ``minHeap.insert(``19``);``        ``minHeap.insert(``6``);``        ``minHeap.insert(``22``);``        ``minHeap.insert(``9``);` `        ``minHeap.print();``        ``System.out.println(``"The Min val is "` `+ minHeap.remove());``    ``}``}`
Output

```The Min Heap is
PARENT : 3 LEFT CHILD : 5 RIGHT CHILD :6
PARENT : 5 LEFT CHILD : 9 RIGHT CHILD :84
PARENT : 6 LEFT CHILD : 19 RIGHT CHILD :17
PARENT : 9 LEFT CHILD : 22 RIGHT CHILD :10
The Min val is 3
```

Using Library Functions
We use PriorityQueue class to implement Heaps in Java. By default Min Heap is implemented by this class.

## Java

 `// Java program to demonstrate working of PriorityQueue``import` `java.util.*;` `class` `Example {` `    ``// Driver code``    ``public` `static` `void` `main(String args[])``    ``{``        ``// Creating empty priority queue``        ``PriorityQueue pQueue = ``new` `PriorityQueue();` `        ``// Adding items to the pQueue using add()``        ``pQueue.add(``10``);``        ``pQueue.add(``30``);``        ``pQueue.add(``20``);``        ``pQueue.add(``400``);` `        ``// Printing the most priority element``        ``System.out.println(``"Head value using peek function:"` `+ pQueue.peek());` `        ``// Printing all elements``        ``System.out.println(``"The queue elements:"``);``        ``Iterator itr = pQueue.iterator();``        ``while` `(itr.hasNext())``            ``System.out.println(itr.next());` `        ``// Removing the top priority element (or head) and``        ``// printing the modified pQueue using poll()``        ``pQueue.poll();``        ``System.out.println(``"After removing an element "``                           ``+ ``"with poll function:"``);``        ``Iterator itr2 = pQueue.iterator();``        ``while` `(itr2.hasNext())``            ``System.out.println(itr2.next());` `        ``// Removing 30 using remove()``        ``pQueue.remove(``30``);``        ``System.out.println(``"after removing 30 with"``                           ``+ ``" remove function:"``);``        ``Iterator itr3 = pQueue.iterator();``        ``while` `(itr3.hasNext())``            ``System.out.println(itr3.next());` `        ``// Check if an element is present using contains()``        ``boolean` `b = pQueue.contains(``20``);``        ``System.out.println(``"Priority queue contains 20 "``                           ``+ ``"or not?: "` `+ b);` `        ``// Getting objects from the queue using toArray()``        ``// in an array and print the array``        ``Object[] arr = pQueue.toArray();``        ``System.out.println(``"Value in array: "``);``        ``for` `(``int` `i = ``0``; i < arr.length; i++)``            ``System.out.println(``"Value: "` `+ arr[i].toString());``    ``}``}`
Output:
```Head value using peek function:10
The queue elements:
10
30
20
400
After removing an element with poll function:
20
30
400
after removing 30 with remove function:
20
400
Priority queue contains 20 or not?: true
Value in array:
Value: 20
Value: 400```

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up