void ReheapDown( int* heap, int top, int swpIndx, int numElements ) {
int leftChild = 2 * top + 1;
int rightChild = 2 * top + 2;
int minChild;
if (leftChild < numElements) {
// find subscript of smallest child
if (rightChild >= swpIndx || heap[leftChild] < heap[rightChild])
minChild = leftChild;
else
minChild = rightChild;
// if data at top is greater than smallest
// child then swap and continue
if (heap[top] > heap[minChild]) {
swap( heap[top], heap[minChild] );
ReheapDown( heap, minChild, swpIndx, numElements );
}
}
This is for a simple heap. ReheapDown is used partly for removing items in the heap. What does swpIndx do though? (I need to know to do a homework assignment, where I’m supposed to write the function that removes a certain key in the heap.)
To remove a key from a heap, we might want to swap it with the last key in the heap before deleting it, otherwise there would be a gaping hole in the heap.
However, swapping the last node with the node we want to remove can upset the ordering of the heap, which is where that ReheapDown method that you provided comes in.
I believe the swpIndex parameter is the index into which we have placed the element that we wish to remove. So that part of the code basically says:
I think that parameter is unnecessary though, since it seems that it’s only purpose is to check for the existence of the left and right child; this can also be accomplished by comparing the leftChild and rightChild indices to numElements.
Hope this helps 🙂