8.4 Priority QueuesSome applications require the use of a queue in which items are assigned a priority and the items with a higher priority are dequeued first. However, all items with the same priority still obey the FIFO principle. That is, if two items with the same priority are enqueued, the first in will be the first out. The Priority Queue ADTA priority queue is simply an extended version of the basic queue with the exception that a priority must be assigned to each item at the time it is enqueued. There are two basic types of priority queues: bounded and unbounded. The bounded priority queue assumes a small limited range of priorities over the interval of integers . The unbounded priority queue places no limit on the range of integer values that can be used as priorities. The definition of the Priority Queue ADT is provided below. Note that we use one definition for both bounded and unbounded priority queues, but with two different constructors. The Priority Queue ADT
Example UseConsider the following code segment, which enqueues a number of items into a priority queue: Q = PriorityQueue() Q.enqueue("purple", 5) Q.enqueue("black", 1) Q.enqueue("orange", 3) Q.enqueue("white", 0) Q.enqueue("green", 1) Q.enqueue("yellow", 5) The abstract view of the resulting queue is shown in Figure 8.4.1. The first item to be removed will be the first item with the highest priority. Notice when items To illustrate the use of the priority queue, the following code segment removes the items and prints them to the terminal: while not Q.isEmpty() : item = Q.dequeue() print(item) which results in the following output: white black green orange purple yellow
|