next up previous index
Next: Implementation of Priority Queues Up: Removal Algorithm Previous: Removal Algorithm   Index


Code for remove

Suppose again that the heap is represented by an array heap containing a certain number of elements which we refer to by the variable size. Then the code in Figure 9.3 will implement the algorithm just described. Note that it is again not necessary to actually insert the 17 at the top of the heap initially. It is only necessary to promote lower items upwards along a suitable path until the correct place is found to insert the 17.

Figure 9.3: Java code for remove.
public Comparable remove() {
    if (size == 0) {
        throw new NoSuchElementException();
    }
    Comparable result = heap[0];
    Comparable item = heap[--size];
    int child, parent = 0; 
    while ((child = (2 * parent) + 1) < size) {
        if (child + 1 < size && heap[child].compareTo(heap[child + 1]) < 0) {
            ++child;
        }
        if (item.compareTo(heap[child]) < 0) {
            heap[parent] = heap[child];
            parent = child;
        } else {
            break;
        }
    }
    heap[parent] = item;
    return result;
}

If the heap is empty (size == 0) an exception must be raised; otherwise the item to be returned is heap[0] and the item to be reinserted is heap[size-1], which we access as heap[--size], thereby also decreasing the size of the heap. We begin with parent in the root position. The initial values of parent and children are shown below.


\begin{picture}(380,250)(-120,60)
\put(110,235){\line(5,-4){55}}
\put(70,235){...
...\makebox(0,0){\texttt{child+1}}}
\put(240,180){\vector(-1,0){35}}
\end{picture}
The while loop examines the two children of parent. The first if statement tests whether there are two children (child+1 < size). If so, it compares the values located at the two children and sets child to be the location of the larger. The second if statement then compares the item to be demoted with the value at this child. If the item is strictly less than the value at the child, the child value is promoted. Otherwise, we are done and the item can be inserted in the parent position. Finally we return the item of highest priority.


next up previous index
Next: Implementation of Priority Queues Up: Removal Algorithm Previous: Removal Algorithm   Index
Peter Williams 2005-06-07