Reputation: 314
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.
Upvotes: 1
Views: 74
Reputation: 39807
The problem is with how you're recursing. You're recursing with max_heap(key--);
which effectively means "first call max_heap(key);
and then set key = key - 1;
". This gives you an endless loop since each call to your function is made with the same key that was originally provided. You will get better results if you pre-decrement (max_heap(--key);
).
That being said, this is not a good problem to solve with recursion. A while loop would be much better.
Upvotes: 4