Inserting into a heap-tree is relatively straightforward. Because we
keep of the largest position n which has been filled so far, we
can insert the new element at position
, provided there
is still room in the array. This will once again give us a complete
binary tree, but the heap-tree property might, of course, be violated
now. Hence we may have to `bubble up' the new element. This is done
by comparing its priority with that of its parent, and if the new
element has higher priority larger, then it is exchanged with its
parent. We may have to repeat this process, but once we reach a parent
that has bigger or equal priority, we can stop. Inserting a node takes
at most
steps because the number of times that we may have to
`bubble up' the new element depends on the height of the tree. Here
is an algorithm
insert(int v) {
if (n < MAX) {
n = n + 1;
heap[n] = v;
bubble_up(n);
}
else
raise an exception because we've run out of space;
}
bubble_up(int i) {
while (not isroot(i) and heap[i] > heap[parent(i)]) {
swap heap[i] and heap[parent(i)];
i = parent(i);
}
}