Min Heap in Java
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 an index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.
5 13 / \ / \ 10 15 16 31 / / \ / \ 30 41 51 100 41
Let us go through the representation of Min heap. So basically 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.
Now let us discuss the operations on Min Heap which is as follows:
- getMin(): It returns the root element of Min Heap. The Time Complexity of this operation is O(1).
- extractMin(): Removes the minimum element from MinHeap. The Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root.
- insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If a 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.
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
We use PriorityQueue class to implement Heaps in Java. By default Min Heap is implemented by this class which is as shown in below example as follows:
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.