Learn-dsa..in 30 days!



























CC-13 : Convert Min Heap to Max Heap.

Description:

Given an Min Heap as input, convert it into a Max Heap.

Test cases and expected outputs:

Input Parameters Expected outputs
Min Heap :
[0] = 1
[1] = 2
[2] = 3
[3] = 4
[4] = 5
[5] = 6
[6] = 7
Max Heap :
[0] = 7
[1] = 5
[2] = 6
[3] = 4
[4] = 2
[5] = 1
[6] = 3

Pseudocode:

Method minToMaxHeap(int[] arr):

Set n=arr.length.
Iterate on arr from index (n/2)-1 to index 0:
Call updateHeap(arr, idx).

UpdateHeap() (also known as Heapify() method):

This method takes heap array named arr and index idx of heap array as input variable.
It moves the node data at index idx to its correct position in the Max Heap.
If node data at left child index of idx or right child index of idx is greater than node data at index idx:
Node data at index idx and its child index childIdx with greater node data is swapped.
UpdateHeap() is recursively called with the index of the child childIdx .

Code:

public void updateHeap(int[] heap, int idx) {
	int parentIdx=idx;
	int leftChildIdx= 2*idx+1;
	int rightChildIdx=2*idx+2;
	if ((leftChildIdx < heap.length) && (heap[leftChildIdx] > heap [parentIdx])) {
		parentIdx=leftChildIdx;
	}
	if ((rightChildIdx < heap.length) && (heap[rightChildIdx] > heap [parentIdx])) {
		parentIdx=rightChildIdx;
	}
	if (parentIdx != idx) {
		int temp=heap[idx];
		heap[idx]=heap[parentIdx];
		heap[parentIdx]=temp;
		updateHeap(heap, parentIdx);
	}
}

public int[] minToMaxHeap(int[] arr) {
	int n=arr.length;
	for (int idx = (n / 2) - 1; idx >= 0; idx--) {
		updateHeap(arr, idx);
    }
    return arr;
}

Click here to download and run code and test cases !