I am trying to create a max heap , the logic is simple , if parent is smaller then one of its childre, swap them. I tried implementing it using
void maxHeapify( int i , int *a , int n ){
int largest = i;
int left = ( i * 2 ) + 1;
int right = ( i * 2 ) + 2;
if( left < n && a[ largest] < a[ left ])
largest = left;
if( right < n && a[ largest ] < a[right])
largest = right;
if( largest != i ){
swap( a[i], a[largest]);
maxHeapify( largest , a, n );
}
}
int main(){
int n;
int * a;
cout << "Number of elements : ";
cin >> n ;
a = new int[n];
for( int i = 0; i < n ; i++){
cin >> a[i];
}
for( int i = n/2 -1 ; i >= 0 ; i-- ){
maxHeapify( i , a, n);
}
for(int i = 0; i < n ; i++){
cout << a[i] << " ";
}
return 0;
}
i am using input
2 7 26 25 19 17 1 90 3 36
the tree shoud look like
90 36 17 25 26 7 1 2 3 19
so array representation should be 90 36 17 25 26 7 1 2 3 19
yet the output of the code is
90 36 26 25 19 17 1 7 3 2
i looked it up and found many same codes in many tutorials. How come the output isnt representation of the tree in array? Did i misunderstood it?
Thanks for explanation