According to my coding class, the left child is 2 * i
and the right child is 2 * i + 1
.
With this in mind, I coded the following:
void max_heap( int key ){
int leftkey = ( 2 * key ) + 1;
int rigtkey = ( 2 * key ) + 2;
printf( "key is: %d left child index is: %d right child index is: %d \n",
key, leftkey, rigtkey );
printf( "value at key is: %d left child is: %d right child is: %d \n",
heap[key], heap[leftkey], heap[rigtkey] );
if ( key >= 0 ){ // My base case?
if ( leftkey < size && leftkey != size ){
//Makes sure I don't go out of bounds
if ( heap[leftkey] > heap[key] ){
swap( &heap[leftkey], &heap[key] );
}
}
else if ( rigtkey < size && rigtkey != size ){
// Makes sure I don't go out of bounds
if ( heap[rigtkey] > heap[key] ){
swap( &heap[rigtkey], &heap[key] );
}
}
max_heap( key-- );
}
}
I call the method with max_heap(size/2)
, with size being the number of entries in the array.
When I run the program and enter:
1 2 3 4 5 6
The result is:
key is: 3 left child index is: 7 right child index is: 8
value at key is: 4 left child is: 0 right child is: 0
key is: 3 left child index is: 7 right child index is: 8
value at key is: 4 left child is: 0 right child is: 0
key is: 3 left child index is: 7 right child index is: 8
value at key is: 4 left child is: 0 right child is: 0
key is: 3 left child index is: 7 right child index is: 8
value at key is: 4 left child is: 0 right child is: 0
...
It loops forever like that and no swapping is ever done.