next up previous index
Next: Insertion Algorithm Up: Binary Heaps and Priority Previous: Arithmetic of Tree Traversal   Index


Priority Queues

So far we have not said anything about how we might use binary heaps. Two important applications are in priority queues and sorting.

It is frequently useful to modify the queue concept by attaching a priority to items in the queue. For example, jobs waiting in a printer queue, or processes awaiting execution on a processing unit, may have different priorities. The allocation of tickets for a football match, or to standby passengers awaiting an airline flight, or patients needing medical attention, may also be prioritised. If an item of higher priority joins the queue, it can jump to the front or, at least, progress to some place closer to the front. In general the items in the queue will be ranked. We want the item of highest rank in the queue to be served first.

A simple PriorityQueue interface can be given as in Figure 9.1.

Figure 9.1: A simple interface for a priority queue.
public interface PriorityQueue {
    public boolean isEmpty();
    public int size();
    public void add(Comparable item);
    public Comparable remove();
}

Items in a priority queue need to be comparable with respect to order, i.e. to implement the Comparable interface. The items themselves may be complex, e.g. records with several fields, but they must contain some information which enables them to be ordered, and the ordering must have been defined.

If we use a binary heap to implement a priority queue, an item of highest priority will always be at the root of the tree. This makes it very easy to determine the next item to emerge from the queue. But we must then reorganise the heap so that an item of highest priority amongst the remainder moves into the root position. Removal of an item from the heap must leave the heap properly ordered, in other words it must still satisfy the heap property (H). Similarly, when an item is inserted into the heap, it must be placed in the correct position so that (H) remains satisfied.



Subsections
next up previous index
Next: Insertion Algorithm Up: Binary Heaps and Priority Previous: Arithmetic of Tree Traversal   Index
Peter Williams 2005-06-07