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:
start after [2] after [1] after [0] 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.
15 items in 4 levels. At most how many swaps can heapify need, sifting down from the bottom up?