[0][1][2][3][4][5]1import heapq2pq = [5, 3, 8, 1, 4]3heapq.heapify(pq)4heapq.heappush(pq, 2)5out = []6while pq:7 x = heapq.heappop(pq)8 out.append(x)9print(out)[0][1][2][3][4][5][0][1][2][3][4][5]swaps0538142
Value blocks: the items in the heap, on the shelf of their list indexRows: pq (the same list, cell by cell) and outA moving block: one swap, push or popThe Python program on the card builds a min-heap with heapq and pops it empty. The board shows the list as a tree (children of i at 2i + 1 and 2i + 2); the value blocks swap along one path at a time. Each pop sends the smallest item into out, so out ends sorted: heapsort.

A priority queue

  1. 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.

Popping

Heapsort

What happens

;; step 1/8 · pq-idea
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

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.