Learn-dsa..in 30 days!



























CC-10 : Check if input array represents a Max Heap.

Description:

Check if input array represents a Max Heap.

Test cases and expected outputs:

Input Parameters Expected outputs
Heap1 :
[0] = 92
[1] = 44
[2] = 67
[3] = 43
[4] = 12
[5] = 21
[6] = 55
Is Max Heap: true
Heap 2 :
[0] = 22
[1] = 44
[2] = 67
[3] = 43
[4] = 12
[5] = 21
[6] = 55
Is Max Heap: false

Pseudocode:

This method takes input array of integers names as nums as a parameter.
Iterate though nums from index 0 to index nums.length-1:
For each index idx, check the integers at position (2*idx)+1, if it is greater than nums[idx], then input array does not represent a Max Heap, so return false.
Else, for each index idx, check the integers at position (2*idx)+2, if it is greater than nums[idx], then input array does not represent a Max Heap, so return false.
If we have not exited with false status in above loop, then the array represents a Max Heap, so return true.

Code:

public boolean isMaxHeap(int maxHeap[]) {
	for (int idx=0; idx< maxHeap.length;idx++) {
		int leftChildIdx=2+idx+1;
		if (leftChildIdx < maxHeap.length-1) {
			if (maxHeap[idx] < maxHeap[leftChildIdx]) {
				return false;
			}
		}
		int rightChildIdx=2+idx+2;
		if (rightChildIdx < maxHeap.length-1) {
			if (maxHeap[idx] < maxHeap[rightChildIdx]) {
				return false;
			}
		}
	}
	return true;
}

Click here to download and run code and test cases !