Learn-dsa..in 30 days!



























CC-2 : Implement Min Heap

Description:

Create and test a custom Min Heap implementation. Each parent node needs to be lesser than its children at all levels.

For each node at index idx, its left child will be stored at index ((2*idx)+1)) and right child will be stored at index ((2*idx)+2).

Test cases and expected outputs:

Input Parameters Expected outputs
HeapMin hp=new HeapMin();
hp.insert(43);
hp.insert(92);
hp.insert(21);
hp.insert(44);
hp.insert(12);
hp.insert(67);
hp.insert(55);
retVal=hp.getMinHeap();
printArray(retVal, "Min Heap");
Min Heap :
[0] = 12
[1] = 21
[2] = 43
[3] = 92
[4] = 44
[5] = 67
[6] = 55
hp.deleteTop();
retVal=hp.getMinHeap();
printArray(retVal, "Min Heap after top deletion");
Min Heap after top deletion :
[0] = 21
[1] = 44
[2] = 43
[3] = 92
[4] = 55
[5] = 67

Addition of node to Heap.

Pseudocode:

Implement the following methods, code is mostly similar to Max Heap, only comparison of parent-child node data in insert() and updateHeap() methods is reversed as shown in code below.

Code:

public class HeapMin {
 
private int[] minHeap=new int[20];
private int currSize;
	
public boolean insert(int num) {
	if (currSize >= minHeap.length) {return false;}
	minHeap[currSize]=num;
	currSize++;
	int idx=currSize-1;
	int parentIdx=(idx-1)/2;
	while ((idx > 0)&& (minHeap[idx] < minHeap[parentIdx])){
		int temp=minHeap[idx];
		minHeap[idx]=minHeap[parentIdx];
		minHeap[parentIdx]=temp;
		idx=parentIdx;
		parentIdx=(idx-1)/2;
	}
	
	return true;
}

public void updateHeap(int idx) {
	int parentIdx=idx;
	int leftChildIdx= 2*idx+1;
	int rightChildIdx=2*idx+2;
	if ((leftChildIdx < currSize) && (minHeap[leftChildIdx] < minHeap [parentIdx])) {
		parentIdx=leftChildIdx;
	}
	if ((rightChildIdx < currSize) && (minHeap[rightChildIdx] < minHeap [parentIdx])) {
		parentIdx=rightChildIdx;
	}
	if (parentIdx != idx) {
		int temp=minHeap[idx];
		minHeap[idx]=minHeap[parentIdx];
		minHeap[parentIdx]=temp;
		updateHeap(parentIdx);
	}
}
}

Click here to download and run code and test cases !