Next: Code for add
Up: Priority Queues
Previous: Priority Queues
  Index
Insertion Algorithm
Consider first the problem of inserting an item into a binary heap.
For definiteness consider heaps of integers. Suppose we have the
binary heap
and we have to insert the number 35. The structure of the new heap is
fixed by the need for it to be a complete binary tree. Since we must
fill each layer from left to right, it must have the form
where, for definiteness, we have placed the 35 in the next vacant
place, although this now violates the heap ordering property. There
is, however, a simple algorithm for restoring the order property. We
have already seen that every path in a heap must be in decreasing
order from root to leaf. But we now have a path
which violates this requirement. The solution is simply to bubble the
35 up the tree until the order of this path is correct. This involves
the sequence of transformations
Making these two exchanges, we obtain the heap
The 35 has been promoted to its proper place. Note that the 35 is
also no less than its left descendant 25. By construction the 35 had
to be no less than its right descendant 31, otherwise we should not
have made the final promotion. But the 31 had to be no less than the
25 in the first place, since the heap was originally well ordered. So
the 35 is also no less than the 25. This illustration should persuade
you of the correctness of the algorithm. We really need a proper
inductive proof. That would be simple but beyond our present span.
Next: Code for add
Up: Priority Queues
Previous: Priority Queues
  Index
Peter Williams
2005-06-07