// Siftdown() finds the children of the node given, compares // their values and swaps them if necessary. It then recurses // on the swapped child since the swap could have upset the // heap property on lower subtrees. void siftDown(int *node){ // base case if(isLeaf(node)) return; int *left = leftChildOf(node), *right = rightChildOf(node); int *min_child = smallest(left,right); if(*node > *min_child) swapValues(min_child, node); // recursion siftDown(min_child); }
/////////////////////////////////////////////////////////////////////////////// // // // FUNCTION NAME: downHeap // // // // PURPOSE: builds a heap from top down // // // // PARAMETERS // // Type/Name: PSTPoint*/array // // Description: The array of points // // // // Type/Name: int/v // // Description: The offset from begin from which to begin building // // the heap. // // // // Type/Name: int/begin // // Description: The first element in the array to be sorted. // // // // Type/Name: int/end // // Description: The last element in the array to be sorted. // // // // RETURN: Void. // // // // NOTES: Note that indices are base zero, i.e. the first // // element has index 0, the second element has index 1... // // // /////////////////////////////////////////////////////////////////////////////// void downHeap(PSTPoint* array, int v, int begin, int end) { int w = leftChildOf(v); // invariant: element at index v has a left child while(begin + w <= end) { // if left child has a sibling if(begin + w+1 <= end) // if right child is greater than left child if(array[begin + w+1] > array[begin + w]) // use right child w++; // if larger child is less than its parent if(!(array[begin + w] > array[begin + v])) return; // otherwise, swap child and parent PSTArray::swap(array,begin + w,begin + v); // continue with child v = w; w = leftChildOf(v); } }