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.
public interface PriorityQueue {
public boolean isEmpty();
public int size();
public void add(Comparable item);
public Comparable remove();
}
|
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.