next up previous index
Next: Code for remove Up: Binary Heaps and Priority Previous: Code for add   Index


Removal Algorithm

Removing an item from a priority queue is simple if the queue is represented by a binary heap. The next item to leave the queue will always be the item at the top of the heap. The only problem is that we have shall now have an empty place (assuming there was more than one item in the heap initially). Since the heap must form a complete binary tree, something must fill this empty place. Furthermore the bottom right position must be vacated, because there will now be one less item in the heap.

Suppose the queue is represented by the heap


\begin{picture}(380,195)(-100,60)
\put(180,180){\makebox(0,0){28}}
\put(90,240...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
and we want to remove an item from the queue. The next item to leave the queue will be the item at the top of the heap, namely 40. The slot containing the last item 17 must now be vacated, so let us place the 17 at the top of the heap obtaining

\begin{picture}(380,195)(-100,60)
\put(90,240){\makebox(0,0){17}}
\put(110,235...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
This is now a complete binary tree, but it is not a heap because the 17 is smaller than both its children. The solution is to demote the 17 from the top, corresponding to the way we promoted items from the bottom on insertion.

In the case of removal, however, we have two children to consider. For promotion, we only had to consider the single parent. The obvious solution is to exchange the 17 with the larger of its two children (if they are the same, it doesn't matter which is chosen). So on the first exchange we get


\begin{picture}(380,195)(-100,60)
\put(90,240){\makebox(0,0){35}}
\put(110,235...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
The 17 must now be compared with its two children, 25 and 31. Again, taking the larger of the two and making the exchange, we finally reach

\begin{picture}(380,195)(-100,60)
\put(0,180){\makebox(0,0){31}}
\put(90,240){...
...
\par\put(130,130){\line(1,1){36}}
\put(230,130){\line(-1,1){36}}
\end{picture}
Since we reached the bottom of the tree, we are done, though we could have terminated before reaching the bottom of the tree. That would have happened if we reached a situation where the 17 was already no less than either of its two children, so that heap order was restored.

The algorithm is simple: put the last item at the top of the heap and then keep exchanging it with the larger of its children until heap order is restored. Again you should satisfy yourself informally that this really does work and then, ideally, prove a theorem.



Subsections
next up previous index
Next: Code for remove Up: Binary Heaps and Priority Previous: Code for add   Index
Peter Williams 2005-06-07