Min Heap
In the context of the heap data structure, a min heap is a complete binary tree where the value of each node is less than or equal to the values of its children. The root node of the min heap contains the minimum value in the heap.
Similar to the max heap, we can represent a min heap in memory using an array. The elements are inserted into the array from left to right, and each element is then arranged in such a way that it satisfies the min heap property.
A min heap supports the following operations:
insert(value)
: Inserts a new element into the min heap while maintaining the min heap property.remove()
: Removes and returns the minimum element from the min heap while maintaining the min heap property.isEmpty()
: Returns true if the min heap is empty, false otherwise.isFull()
: Returns true if the min heap is full, false otherwise.
Here is an implementation of a min heap in Java:
1/* MinHeap class */
2```java
3
4class MinHeap {
5 private int[] heapArray;
6 private int maxSize;
7 private int heapSize;
8
9 public MinHeap(int size) {
10 maxSize = size;
11 heapSize = 0;
12 heapArray = new int[maxSize];
13 }
14
15 // Other methods...
16}
In this implementation, we use an array heapArray
to store the elements in the min heap. The maxSize
variable represents the maximum size of the min heap, while heapSize
represents the current number of elements in the min heap.
The insert(value)
method inserts a new element into the min heap. If the min heap is full, an error message is printed. Otherwise, the new element is inserted at the end of the array and then heapifyUp()
is called to maintain the min heap property.
The remove()
method removes and returns the minimum element from the min heap. If the min heap is empty, an error message is printed. Otherwise, the minimum element is replaced with the last element in the array, and heapifyDown()
is called to maintain the min heap property.
The heapifyUp()
method is used to fix the min heap property from the bottom up. It compares the element at the given index with its parent and swaps them if necessary to maintain the min heap property.
The heapifyDown()
method is used to fix the min heap property from the top down. It compares the element at the given index with its children and swaps them if necessary to maintain the min heap property.
By using the underlying array representation and the heapifyUp()
and heapifyDown()
methods, we can efficiently insert and remove elements while maintaining the min heap property.
xxxxxxxxxx
class MinHeap {
private int[] heapArray;
private int maxSize;
private int heapSize;
public MinHeap(int size) {
maxSize = size;
heapSize = 0;
heapArray = new int[maxSize];
}
// Other methods...
}