Always the smallest first
After this: Say what a priority queue does, and why a list is slow at one of its two jobs.
On this page · 9 sections · 3 checks
Picture the waiting room of a hospital. Patients arrive in any order, and each one gets an urgency score. The doctor does not see people in order of arrival. The doctor always sees the most urgent patient next.
In this tutorial, a smaller number means more urgent. A patient with score 1 goes before a patient with score 5.
Three patients
Here is the smallest example.
- A patient with score 5 arrives.
- A patient with score 3 arrives.
- A patient with score 8 arrives.
- The doctor is free. The waiting room holds 5, 3 and 8. The smallest score is 3, so that patient goes in.
- A new patient with score 1 arrives. The room now holds 5, 8 and 1.
- The doctor is free again. The smallest score is 1, so the newest patient goes in, ahead of the two who have waited longer.
Now think about what a program would have to do here. Only two jobs ever come up: add a patient, and take out the most urgent patient.
The name: a priority queue
A structure that does these two jobs is called a . Each item has a number called its priority. The two jobs have short names.
- Push adds an item.
- Pop takes out the item with the smallest number.
In an ordinary queue, the first to arrive is the first to leave. In a priority queue, the number decides. A stack uses the same two words, but its pop takes the newest item, so take care not to mix them up.
Many programs need this. A printer can let urgent jobs go first. A computer's operating system can choose which program runs next. The shortest-path search in a later tutorial always goes to the closest place next.
The question for this lesson is how to build one that stays fast. We will try two plain ways first.
First try: a plain list
A list from the arrays tutorial is the first thing to try. Each value sits in a numbered box called a cell, and the number is the cell's index. We add each new value at the end, so the three patients make [5, 3, 8].
- Push is cheap. The new value goes at the end, however long the list is.
- Pop is slow. The smallest value could be anywhere, so the program has to look at every value.
[5, 3, 8]needs three looks. A list of 1,000 values needs 1,000 looks, and it needs them for every pop.
Programmers have a short way to say this. The letter n stands for the number of items.
- O(1) means the work stays the same, however many items there are.
- O(n) means the work grows with the number of items: twice as many items, twice as many steps.
The lesson Counting steps explains both. So this list has an O(1) push and an O(n) pop.
Second try: a sorted list
What if the list stays sorted? Then the value we want is always in the same place. We sort it largest first, so that the smallest sits at the end, where it is cheap to remove. The three patients become [8, 5, 3].
Now pop is cheap. It takes the last value, and that is O(1).
But push is slow. The new value has to go in its sorted place, and that place is usually taken. Suppose a patient with score 6 arrives.
- Walk along the list past the values larger than 6. The walk passes 8 and stops at 5, which is at index 1.
- Move 3 one cell to the right.
- Move 5 one cell to the right. Index 1 is now free.
- Write 6 at index 1.
The list is now [8, 6, 5, 3]. Two values moved. A new largest value, such as 9, would move every value in the list. This is the work you saw in inserting in the middle of an array, and it makes push O(n).
Here is that push as code. It belongs to a small class whose list is called self.itemsitems.
def push(self, value): i = 0 while i < len(self.items) and self.items[i] > value: i += 1 # walk past the larger values self.items.insert(i, value) # every value after i moves one cell right void push(int value) { int i = 0; while (i < items.size() && items.get(i) > value) i++; // walk past the larger values items.add(i, value); // every value after i moves one cell right }The while loop is step 1: it moves i past the larger values. The next line does steps 2 to 4: it moves every value after i one cell to the right, then writes the new value.
A faster search would not fix this. A method called binary search can find the spot in a sorted list with far fewer looks, but the values after the spot still have to move.
Neither way is good enough
| How the list is kept | Push | Pop |
|---|---|---|
| Unsorted | O(1) | O(n) |
| Sorted, largest first | O(n) | O(1) |
Each way makes one of the two jobs slow. That matters when the numbers get big. With a million items, one O(n) job can take a million steps. Do that a million times and the total can reach a million million steps.
What a heap gives you
A keeps the smallest item at a known place, but it does not sort the other items. It keeps only as much order as it needs, and that is why both jobs stay cheap. In a heap, push and pop are both O(log n).
O(log n) means that the work grows very slowly. When the number of items doubles, the work goes up by about one step.
| Items | O(n) work | O(log n) work |
|---|---|---|
| 1,000 | 1,000 steps | about 10 steps |
| 1,000,000 | 1,000,000 steps | about 20 steps |
You do not need the maths yet. The lesson Why push and pop are fast shows where log n comes from.
Watch it happen
Here is a heap at work. You will see a row of cells and a tree. They show the same values, and the next lesson explains why.
Push four values in a scrambled order, then pop twice. Do not worry about the swaps for now, because the lessons on push and pop explain them. Watch only what comes out.
- Push 5Push 5. The first value goes at the top of the tree.
- Push 3
- Push 8
- Push 1
- Pop the minimum
- Pop the minimum
- 0
empty
Push a few values and watch them sift up.
Check yourself
A program pushes a job and pops the most urgent job, a million times each. Which structure keeps both push and pop below O(n)?
A SortedListQueue keeps its list sorted largest first. Its push puts each value in its sorted place, and its pop takes the value at the end of the list. What are the last two lines printed?
q = SortedListQueue()for v in [5, 3, 8, 1]: q.push(v) print(q.items)print(q.pop(), q.pop())SortedListQueue q = new SortedListQueue();for (int v : new int[] {5, 3, 8, 1}) { q.push(v); System.out.println(q.items);}System.out.println(q.pop() + " " + q.pop());A priority queue is kept as a sorted list of n items. What does pushing a new item cost, and why?
Connect
The next lesson shows what a heap looks like, and how an array can also be a tree.
- Say what a priority queue does: push adds an item, and pop takes out the item with the smallest number.
- Say why a sorted list makes push O(n), and why an unsorted list makes pop O(n).
- Say what a heap gives you: push and pop are both O(log n), and nothing is ever fully sorted.