Question
Lesson 5: Minimum Heap Implementation Min Heap in Java A Min-Heap is a complete binary tree in which the value in each internal node is
Lesson 5: Minimum Heap Implementation
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 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[0]. 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:
- getMin(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).
- 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.
- 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 dont 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
Source Code
|
Output
|
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started