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
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
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
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
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: Code for remove
Up: Binary Heaps and Priority
Previous: Code for add
  Index
Peter Williams
2005-06-07