Priority Queues
Priority Queues
A priority queue is a more specialized data structure than a stack or a queue. However, it’s a useful tool in a surprising number of situations. Like an ordinary queue, a priority queue has a front and a rear, and items are removed from the front. However, in a priority queue, items are ordered by key value so that the item with the lowest key (or in some implementations the highest key) is always at the front. Items are inserted in the proper position to maintain the order.
Here’s how the mail sorting analogy applies to a priority queue. Every time the postman hands you a letter, you insert it into your pile of pending letters according to its priority. If it must be answered immediately (the phone company is about to disconnect your modem line), it goes on top, whereas if it can wait for a leisurely answer (a letter from your Aunt Mabel), it goes on the bottom. Letters with interme- diate priorities are placed in the middle; the higher the priority, the higher their position in the pile. The top of the pile of letters corresponds to the front of the priority queue.
When you have time to answer your mail, you start by taking the letter off the top (the front of the queue), thus ensuring that the most important letters are answered first. This situation is shown in Figure 4.10.
Like stacks and queues, priority queues are often used as programmer’s tools. We’ll see one used in finding something called a minimum spanning tree for a graph, in Chapter 14, “Weighted Graphs.”
Also, like ordinary queues, priority queues are used in various ways in certain computer systems. In a preemptive multitasking operating system, for example, programs may be placed in a priority queue so the highest-priority program is the next one to receive a time-slice that allows it to execute.
144 CHAPTER 4 Stacks and Queues
Letter on top is always processed
first
More urgent letters are inserted higher
Less urgent letters are inserted lower
FIGURE 4.10 Letters in a priority queue. In many situations you want access to the item with the lowest key value (which
might represent the cheapest or shortest way to do something). Thus, the item with the smallest key has the highest priority. Somewhat arbitrarily, we’ll assume that’s the case in this discussion, although there are other situations in which the highest key has the highest priority.
Besides providing quick access to the item with the smallest key, you also want a priority queue to provide fairly quick insertion. For this reason, priority queues are, as we noted earlier, often implemented with a data structure called a heap. We’ll look at heaps in Chapter 12, “Heaps.” In this chapter, we’ll show a priority queue imple- mented by a simple array. This implementation suffers from slow insertion, but it’s simpler and is appropriate when the number of items isn’t high or insertion speed isn’t critical.