Now we can apply this routine at any node in the tree. Beginning at some given node, which we shall call parent, we can demote the value at this node, if necessary, until it finds its proper place in the heap below parent. Again this will work provided both the left and right sub-trees of parent are already heap ordered. We can write the code for this method, which we call demote, as follows:
private static void demote(Comparable[] heap, int size, int parent) {
Comparable item = heap[parent];
int child;
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;
}
This is much the same as the
remove
method
for the binary heap implementation of priority queues. One difference
is that we no longer return an item, we merely exchange the data in
array elements. The method now takes the heap array as a
parameter, as well as its size. It also takes as a parameter
the parent node whose value is to be demoted, if necessary.
This is the node in the binary tree at which we begin. Remember that
all the method does is to demote the value at parent by
successively exchanging it with the larger of its children, assuming
it has any, until heap order is restored. Again note that this will
make the binary tree rooted at parent into a binary heap,
provided both left and right subtrees of the tree rooted at parent were already binary heaps.