next up previous index
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


\begin{picture}(380,195)(-100,60)
\put(90,240){\makebox(0,0){40}}
\put(110,235...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
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

\begin{picture}(380,195)(-100,60)
\put(20,60){\makebox(0,0){35}}
\par\put(90,24...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
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

\begin{displaymath}
(40, 31, 17, 35)
\end{displaymath}

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

\begin{displaymath}
(40,31,17,{\bf 35}) \mapsto
(40,31,{\bf 35},17) \mapsto
(40,{\bf 35},31,17)
\end{displaymath}

Making these two exchanges, we obtain the heap

\begin{picture}(380,195)(-100,60)
\put(0,180){\makebox(0,0){35}}
\put(90,240){...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
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 up previous index
Next: Code for add Up: Priority Queues Previous: Priority Queues   Index
Peter Williams 2005-06-07