Contents    Page-10    Prev    Next    Page+10    Index   

Removal from Heap

Finding the item to remove with deleteMin is easy: the smallest item is at the root, array position [1]. Removing the top element creates a hole at the top, and we must somehow move the last element in the array into the hole in order to keep the tree complete.

To maintain the order property, we see whether the last element can be put into the hole. If so, we are done; if not, exchange the hole with its smaller child and repeat.


public AnyType deleteMin( ) {
  AnyType top = array[1];
  int hole = 1;
  boolean done = false;
  while ( hole * 2 < currentSize && ! done )
   { int child = hole * 2;
     if ( array[child]
             .compareTo( array[child + 1] ) > 0 )
        child++;    // child now points to smaller
     if (array[currentSize]
             .compareTo( array[child] ) > 0 )
        { array[hole] = array[child];
        hole = child; }
      else done = true; }
  array[hole] = array[currentSize--];
  return top; }