Priority queues and heapsort
About this lesson
A priority queue always hands back its smallest item first. Python's heapq module keeps one inside a plain list, as a binary min-heap. Follow a short Python program as heapify builds the heap, heappush adds an item that rises into place, and heappop takes the root while the last item sinks to fill the gap. Pop every item and they come out sorted: that is heapsort, in O(n log n) time. The lesson "Binary heaps: sift up and sift down" covers the two repair moves in detail, and the Software lesson on hash maps opens this module.
Smallest out first
A priority queue is a waiting line where the smallest item always leaves first, whatever order items arrived in. It has two moves: push adds an item, pop removes the smallest. Python’s heapq module keeps one inside a plain list, here pq.
priority queue: push(item), pop() -> smallest item pq = [5, 3, 8, 1, 4] a plain list is not a heap yet: 1 is not at the front heapq stores a binary min-heap inside a Python list
Read the lesson step by step
Smallest out first
A priority queue is a waiting line where the smallest item always leaves first, whatever order items arrived in. It has two moves: push adds an item, pop removes the smallest. Python’s heapq module keeps one inside a plain list, here pq.
priority queue: push(item), pop() -> smallest item pq = [5, 3, 8, 1, 4] a plain list is not a heap yet: 1 is not at the front heapq stores a binary min-heap inside a Python listheapify builds the heap
Read the list as a tree: item i has children at 2i + 1 and 2i + 2. heapify works from the last parent back to the root, sinking each item below its smaller child. 3 swaps put 1 on top.
heapq.heapify(pq) rearranges pq in place children of i: 2i + 1 and 2i + 2 swap [1] and [3] swap [0] and [1] swap [1] and [3] pq = [1, 3, 8, 5, 4] every parent <= its children, so pq[0] is the smallestpush: add, then rise
heappush(pq, 2) appends 2 at the end, index 5, the next free leaf. Its parent 8 is bigger, so they swap. The new parent 1 is smaller, so 2 stops. One path, at most the tree’s height in swaps.
heapq.heappush(pq, 2) append 2 at [5] swap [5] and [2] (2 < 8) parent [0] = 1 <= 2: stop pq = [1, 3, 2, 5, 4, 8]pop takes the root
heappop(pq) returns pq[0], the smallest item: 1. The loop appends it to out. No search is needed, because the heap always keeps its smallest item at the root.
x = heapq.heappop(pq) x = pq[0] = 1 out = [1] the root is now empty: the heap must be repairedThe last item sinks
To fill the gap, the last item, 8, moves to the root and the list gets one shorter. 8 sinks: it swaps with its smaller child, 2, and stops at a leaf. The smallest left, 2, is on top again.
move pq[5] = 8 to pq[0], drop the last cell swap [0] and [2] (smaller child) pq = [2, 3, 8, 5, 4] swaps for this pop: 1Keep popping
The while loop repeats until pq is empty. Each pop takes the root, moves the last item up and sinks it. Out come 2, 3, 4, 5, 8: each time, the smallest item still waiting.
while pq: (an empty list is false) pop 2 pq = [3, 4, 8, 5] swaps 1 pop 3 pq = [4, 5, 8] swaps 1 pop 4 pq = [5, 8] swaps 1 pop 5 pq = [8] swaps 0 pop 8 pq = [] swaps 0 out = [1, 2, 3, 4, 5, 8]That is heapsort
print(out) shows [1, 2, 3, 4, 5, 8]: sorted. Build a heap, then pop every item: that is heapsort. Any priority queue sorts this way. This version fills a second list; the classic heapsort reuses the same list instead.
print(out) [1, 2, 3, 4, 5, 8] heapsort = build a heap + pop n times textbook heapsort (CLRS ch. 6) works in place: max-heap; swap the root with the last item, shrink the heap by one, sink the new rootWhy it is fast
A push or pop moves one item along a single root-to-leaf path: at most the height, ⌊log₂ n⌋ swaps, here 2. The whole run took 8 swaps. n pops cost O(n log n); heapify only O(n). Heapsort: O(n log n).
n = 6, height = floor(log2 6) = 2 swaps: heapify 3, push 1, pops 1 + 1 + 1 + 1 + 0 + 0 total 8 push, pop: O(log n) each heapify: O(n) heapsort: O(n) + n x O(log n) = O(n log n)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01After heapq.heapify(pq), where is the smallest item?
A min-heap keeps every parent no bigger than its children, so the smallest item is always the root, pq[0]. The rest of the list is not sorted.
02The heap is [1, 3, 2, 5, 4, 8]. What does it look like after one heapq.heappop?
heappop returns 1. The last item, 8, moves to the root, then sinks: its children are 3 and 2, so it swaps with the smaller one, 2, and lands on a leaf. Result: [2, 3, 8, 5, 4].
03A heap holds n items. At most how many swaps does one push or one pop need?
Each push or pop moves one item along a single path between the root and a leaf, so it swaps at most ⌊log₂ n⌋ times. With 6 items that is 2.
04Why is heapsort O(n log n) even though heapify is only O(n)?
Building the heap costs O(n), but taking every item out needs n pops at O(log n) each. The pops dominate: O(n) + O(n log n) = O(n log n).
05The lesson's program sorts into a second list called out. How does classic heapsort avoid that extra list?
The heap and the sorted part share one array. Each round moves the largest item into the slot the heap just gave up at the end, so the array fills up sorted from the back (CLRS chapter 6).
Glossary
- Priority queue
- A collection where you can add items (push) and always remove the smallest (or largest) one first (pop).
- Binary min-heap
- A tree kept in a list where every parent is no bigger than its children. The item at index i has children at 2i + 1 and 2i + 2.
- Root
- The top of the tree, index 0 of the list. In a min-heap it holds the smallest item.
- heapify
- heapq.heapify(list) rearranges a list into a min-heap in place, in linear time.
- Sift down
- Repair move: swap an item with its smaller child until no child is smaller. Used by pop and heapify.
- Sift up
- Repair move: swap an item with its parent while the parent is bigger. Used by push.
- Heapsort
- Sorting by building a heap and then removing the top item n times. O(n log n) time.
- Height
- The number of levels below the root. A heap with n items has height ⌊log₂ n⌋.
Notes and sources
- heapq is a min-heap: the smallest item is at pq[0]. CLRS and Sedgewick & Wayne describe max-heaps, with the largest on top; the rules are the same with every comparison flipped. Since Python 3.14 heapq also has max-heap functions such as heappush_max.
- CPython’s heappop and heapify use a variant of sift down that makes fewer comparisons: it moves the hole all the way to a leaf, then lets the item rise back. With distinct values it ends with the same list as the swap-by-swap version drawn here.
- This program sorts into a second list, which costs O(n) extra memory. Classic heapsort (CLRS chapter 6, Sedgewick & Wayne §2.4) works inside one array: build a max-heap, swap the root with the last item, shrink the heap by one and sink the new root, n times.
- Heapsort is not stable: two equal items can come out in a different order from how they went in. For tasks with equal priority, the Python docs suggest storing (priority, count, task) so the count breaks ties.
- Why is heapify only O(n)? Most items are near the bottom and can sink only a step or two; only the root can sink the full height. MIT 6.006 shows the total is O(n). Pushing the items one by one instead costs O(n log n).
Quiz Unlocks after the last step.