How to check if a given array represents a Binary Heap ? | C program to check whether a given array represents a max - heap or not ; Returns true if arr [ i . . n - 1 ] represents a max - heap ; Start from root and go till the last internal node ; If left child is greater , return false ; If right child is greater , return false ; Driver program
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE bool isHeap ( int arr [ ] , int n ) { for ( int i = 0 ; i <= ( n - 2 ) / 2 ; i ++ ) { if ( arr [ 2 * i + 1 ] > arr [ i ] ) return false ; if ( 2 * i + 2 < n && arr [ 2 * i + 2 ] > arr [ i ] ) return false ; } return true ; } int main ( ) { int arr [ ] = { 90 , 15 , 10 , 7 , 12 , 2 , 7 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; isHeap ( arr , n ) ? printf ( " Yes " ) : printf ( " No " ) ; return 0 ; }