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

Heapify builds a heap in O(n), sifting down from the bottom up

Pushing n items one at a time costs O(n log n) in the worst case. A list you already have can become a heap faster. Every leaf is already a heap of one item. So sift down every parent, from the last parent back to the root. The last parent is index n // 2 - 1.

def heapify(a):
    for i in reversed(range(len(a) // 2)):
        sift_down(a, i)

Here it is on the list from the start of the lesson. Each row is the list after one sift down:

Heapify, one sift down at a time
start
01234563012457211860
after [2]
01234563012187214560
after [1]
01234563071812214560
after [0]
01234567121830214560

45 swaps with 18, then 12 with 7, then 30 sinks past 7 and 12. Green cells moved in that step.

The last row is the same list heapq.heapify gave.

Why is that linear? Look at where the items sit. Half of them are leaves and never move. A quarter sit one level up and can sink one level at most. An eighth can sink two levels at most, and so on. The long walks belong to the few items near the top.

Predict

15 items in 4 levels. At most how many swaps can heapify need, sifting down from the bottom up?

Pick an answer above to see the rest