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:
(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.