6/40
Part 2 of 8 · The heapLearn and do

Pop: move the last item to the top, then swap it down with its smaller child until neither is smaller

A pop takes the top item, and then has to fill the hole it leaves.

def pop(heap):
    last = heap.pop()
    if not heap:
        # it was the only item
        return last
    top, heap[0] = heap[0], last
    sift_down(heap, 0)
    return top

You can't just delete index 0, because that leaves a hole at the top. So take the root, and move the last item into its place. Then push that item down: while one of its children is smaller, swap it with the smaller child. That's called sifting down, and you write the sift_down this code calls.

Here's a pop from the list the push left. 30 is green as it moves down, and its children are orange.

Popping 7
1. 30 moved to index 0
012345630101812214560
2. swapped with 10
012345610301812214560
3. swapped with 12
012345610121830214560

30 swaps with the smaller child each time. At index 3 its children would sit at 7 and 8, past the end, so it stops.

It has to be the smaller child. That child moves up and becomes the parent of the other one. In row 1 of the figure, swapping 30 with 18 instead would put 18 above 10.

A pop compares twice per level: once to find the smaller child, and once against the item. Sedgewick and Wayne's algorithms booksite gives the bound: at most 1 + lg n compares for a push, and at most 2 lg n for a pop, where lg n is log⁡2n\log_2 n. They state it for a max-heap, and it's the same for a min-heap.

These two functions, with the sift_down you're about to write, matched heapq pop for pop over 20,000 random pushes and pops.

In the editor, sift_down(heap, i) has its loop and its swap already. Fill in the middle, which sets smallest to the index of the smallest of the item and its children.