ENع
←Priority queues
Lesson 13 · Hashing and heaps

Priority queues and heapsort

14 min8 steps5 questionsIntermediate
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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 13 · Interactive
01 / 08

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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
  2. heapify 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 smallest
  3. push: 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]
  4. 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 repaired
  5. The 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: 1
  6. Keep 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]
  7. 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 root
  8. Why 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)

Quiz Unlocks after the last step.