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

Code for add

Suppose the heap is represented by an array heap of objects implementing the Comparable interface, and that it contains a certain number of elements which we refer to by the variable size. Assume that size is less than the length of the heap array. The actual heap array may be considerably larger. For instance, in our example, size is initially 9. Then the code in Figure 9.2 will implement the algorithm just described.

Figure 9.2: Java code for add.
public void add(Comparable item) {
    int parent, child = size++;
    while (child > 0 && heap[parent = (child - 1) / 2].compareTo(item) < 0) {
        heap[child] = heap[parent];
        child = parent;
    }
    heap[child] = item;
}

Note that there is no real need to insert the 35 initially in the vacant slot, as we originally described. All we need do is slide the existing members down and then insert the 35 in the correct place. This is what we have done in the Java code. The variable child is initially set to size which is the first vacant slot. The initial values of child and parent are shown here:


\begin{picture}(380,195)(-100,60)
\put(90,240){\makebox(0,0){40}}
\put(110,235...
...}
\put(70,60){\vector(-1,0){44}}
\put(60,170){\vector(0,-1){30}}
\end{picture}
The check that (child > 0) is to ensure that we have not reached the root of the tree (e.g. if we made an insertion into an empty heap). We continue swapping the items stored at parent and child until the path would be properly ordered if we inserted item in the child location. Note that parent always occurs at (child-1)/2 provided (child > 0), otherwise child is the root and doesn't have a parent. We exit the while loop when we have either reached the root, or the parent holds a value no less than the item. The item to be inserted is now placed in the child location.


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