Down-Heapify

void Down_Heapify( vector<int> & data, unsigned int i )
{
  unsigned int left = left_child( i );
  unsigned int right = right_child( i );
  bool hasleft = left < data.size();
  bool hasright = right < data.size();

  // data[i] is a leaf
  if( !hasleft && !hasright )
    return;

  // heap property is satisfied
  // left child is greater than parent and right child is greater than
  // parent if it exists
  if( hasleft && data[i] <= data[ left ]
      && ( ( hasright && data[i] <= data[ right ] )
	   || !hasright ) )
    return;

  // Otherwise, swap data[i] and the smaller of its children.
  unsigned int smaller;
  if( hasright && data[ right ] <= data[ left ] ) 
    smaller = right;
  else
    smaller = left;

  swap( data, i, smaller );
  
  // Start again on the child that changed (i.e., move data[i] down).
  Down_Heapify( data, smaller );
}

Look at node i (initially the root).

We know that the only node that may violate the heap property is a child of the new i. (Why?)

Kind of like bubblesort or insertion sort in a tree. The root value trickles down until it stops.

Running Time? (Maximum number of comparisons and swaps.)


next up previous
Next: Up-Heapify Up: HEAPS Previous: Maintaining the Heap Property