Heapify
medium 16 minHeapify is how a binary heap repairs itself.
Video lesson · Chapter 1 of 5
A bubble has one path up
Bottom-up heapify — The diving-bell winch
1:26Reel
Read caption
Vik builds a min-heap from seven randomly loaded diving bells, sifting down through already repaired subtrees. Fix the low hooks first. Most bells barely move.
How it works
Step through the idea, or press Play.
Spot the violation. One value is in the wrong place: too small for its children, or too big for its parent
Understand it
Start here
What heapify means
A binary heap keeps one rule: in a max-heap every parent is at least as big as its children (in a min-heap, at most). Inserts and removals break that rule at exactly one spot. Heapify is the family of small routines that move the misplaced value up or down until the rule holds again, and the bottom-up loop that applies them to turn a whole array into a heap. Think of a championship bracket where each winner must beat the players below; someone in the wrong round climbs or drops until they fit.
Sift down
A value is smaller than a child. Swap it with the larger child, repeat. Used after pop and in build-heap. .
Sift up
A value is bigger than its parent. Swap it with the parent, repeat. Used after push. .
Build heap
Sift down every parent from back to 0. Surprisingly .
- 1ViolationHeap property broken at one node
- 2CompareNode against parent or children
- 3SwapExchange with the winner
- 4RepeatOne level further
- 5RestoredValue fits, stop
The loop runs at most once per level, so a single sift costs $O(\log n)$.
Foundations
The heap lives in an array
A heap is a complete binary tree, so it packs into a list level by level with no gaps and no pointers. Moving between parent and child is arithmetic on the index. Heap properties covers the shape and order rules in full.
Index arithmetic (0-based)
The max-heap [50, 40, 30, 10, 20]
| Index | Value | Parent | Children |
|---|---|---|---|
| 0 | 50 (root) | none | 1 and 2: 40, 30 |
| 1 | 40 | : 50 | 3 and 4: 10, 20 |
| 2 | 30 | : 50 | 5, 6: out of range, a leaf |
| 3 | 10 | : 40 | leaf |
| 4 | 20 | : 40 | leaf |
Operation 1
Sift down: sink a value
sift_down(heap, i, n) in a max-heap
def sift_down(heap, i, n): while True: largest = i left, right = 2 * i + 1, 2 * i + 2 if left < n and heap[left] > heap[largest]: largest = left if right < n and heap[right] > heap[largest]: largest = right if largest == i: return heap[i], heap[largest] = heap[largest], heap[i] i = largesth = [10, 50, 30, 40, 20]sift_down(h, 0, len(h))print(h) # [50, 40, 30, 10, 20]: 10 swapped with 50, then with 40The contract
Sift down assumes healthy subtrees
Sift down (often called heapify(arr, n, i)) only repairs node . It is correct only if both subtrees of $i$ are already heaps: then the maximum of the subtree must be or one of its two children, so one comparison round finds it. In [3, 9, 6, 4, 8, 1, 5] both subtrees are heaps; sifting 3 down gives [9, 8, 6, 4, 3, 1, 5], a valid heap.
Precondition holds
- [3, 9, 6, 4, 8, 1, 5]: left 9 over 4, 8 and right 6 over 1, 5 are heaps.
- 3 sinks below 9, then below 8, and stops on a leaf.
- Result [9, 8, 6, 4, 3, 1, 5] is a heap.
Precondition broken
- [3, 9, 5, 4, 8, 1, 6]: the right subtree has 5 above 6.
- The same call follows 3 down the left side only.
- Result [9, 8, 5, 4, 3, 1, 6] still has 5 < 6.
Cost of one sift down
Operation 2
Sift up: bubble a value
Insert puts the new value in the next free slot, the end of the array, which keeps the tree complete. If it is bigger than its parent, swap and repeat. Only one comparison per level, against the parent. Inserting 20 into [15, 13, 10, 9, 8, 5, 7]: append at index 7 under 9, then swap past 9, 13 and 15 to reach the root: [20, 15, 10, 13, 8, 5, 7, 9]. More in heap operations.
sift_up(heap, i) in a max-heap
def sift_up(heap, i): while i > 0: parent = (i - 1) // 2 if heap[i] > heap[parent]: heap[i], heap[parent] = heap[parent], heap[i] i = parent else: breakdef push(heap, value): heap.append(value) sift_up(heap, len(heap) - 1)h = [50, 30, 40, 10, 20]push(h, 60)print(h) # [60, 30, 50, 10, 20, 40]h = [15, 13, 10, 9, 8, 5, 7]push(h, 20)print(h) # [20, 15, 10, 13, 8, 5, 7, 9]Push 60 into [50, 30, 40, 10, 20]
| i | Parent | Compare | Array after |
|---|---|---|---|
| 5 | 2 (40) | : swap | [50, 30, 60, 10, 20, 40] |
| 2 | 0 (50) | : swap | [60, 30, 50, 10, 20, 40] |
| 0 | none | at the root: stop | [60, 30, 50, 10, 20, 40] |
Side by side
Sift up vs sift down
| Sift up | Sift down | |
|---|---|---|
| Direction | Toward the root | Toward the leaves |
| Compares with | Parent only | Both children |
| Comparisons per level | 1 | 2 |
| Used after | Insert (push) | Extract (pop), and in build-heap |
| Cost bounded by | Depth of the node | Height of the node |
| Time |
Which direction?
Operation 3
Build a heap bottom up
Leaves are already one-node heaps. Start at the last parent and sift each node down, moving left to the root. When a node is processed both of its subtrees are heaps, which is exactly the contract above. Heap sort uses this as its first phase and walks [4, 10, 3, 5, 1] to [10, 5, 3, 4, 1] step by step.
build_max_heap(a)
Worked example: [3, 15, 13, 9, 8, 5, 10, 4, 1, 6, 17]
- 1
Setup
, last parent . Slots 5 to 10 are leaves.
- 2
i = 4 (8)
Children 6 and 17: swap with 17. 8 lands on a leaf.
- 3
i = 3 (9), i = 2 (13)
9 beats 4 and 1; 13 beats 5 and 10. No swaps.
- 4
i = 1 (15)
Children 9 and 17: swap with 17. 15 then beats 6 and 8, stop.
- 5
i = 0 (3)
3 sinks below 17, then 15, then 8: three levels, the full height.
- 6
Done
[17, 15, 13, 9, 8, 5, 10, 4, 1, 6, 3]after 16 comparisons and 5 swaps.
More inputs
| Input | After build | Comparisons | Swaps |
|---|---|---|---|
| [4, 10, 3, 5, 1] | [10, 5, 3, 4, 1] | 6 | 2 |
| [1, 2, 3, 4, 5] | [5, 4, 3, 1, 2] | 6 | 3 |
| [1, 2, 3, 4, 5, 6, 7] | [7, 5, 6, 4, 2, 1, 3] | 8 | 4 |
| [9, 7, 6, 5, 4, 3, 2] | unchanged: already a heap | 6 | 0 |
| [15, 10, 13, 8, 9, 5, 7] | unchanged: already a heap | 6 | 0 |
Deep dive
Why build-heap is O(n)
Calling an routine about times looks like . But a sift down costs the height of its node, not , and short nodes dominate: half the nodes are leaves (height 0), a quarter have height 1, an eighth height 2, and only the root has height .
Worst-case swaps for a 15-node heap
| Height h | Nodes | Swaps each, at most | Work |
|---|---|---|---|
| 0 (leaves) | 8 | 0 | 0 |
| 1 | 4 | 1 | 4 |
| 2 | 2 | 2 | 4 |
| 3 (root) | 1 | 3 | 3 |
| Total | 15 | 11, less than |
The sum Σ h / 2^h
Why the series is 2
Head to head
Bottom-up build vs n inserts
You could also build a heap by pushing the values one at a time. Each push sifts up and pays the depth of its slot, and most slots are deep: half of all nodes sit on the bottom level at depth about .
Cost of n inserts
| n | Bottom up (sift down), worst swaps | n inserts (sift up), worst swaps | |
|---|---|---|---|
| 7 | 4 | 10 | about 20 |
| 15 | 11 | 34 | about 59 |
| 1,023 | 1,013 | 8,194 | about 10,229 |
| 1,000,000 | 999,993 | about 18 million | about 19.9 million |
In Python
heapq.heapify
Python's heapq module runs these routines on a plain list. heapq.heapify(xs) is the bottom-up build: in place, , returns None. It always makes a min-heap, so xs[0] is the smallest value.
import heapqtasks = [5, 3, 8, 1, 9, 2]heapq.heapify(tasks) # O(n), in placeprint(tasks) # [1, 3, 2, 5, 9, 8]heapq.heappush(tasks, 0) # sift up: O(log n)print(heapq.heappop(tasks)) # 0, then sift down: O(log n)scores = [40, 90, 70, 20]max_heap = [-s for s in scores] # negate for a max-heapheapq.heapify(max_heap)print(-max_heap[0]) # 90| Call | What it does | Time |
|---|---|---|
heapify(xs) | Bottom-up build, min-heap | |
heappush(xs, v) | Append, then sift up | |
heappop(xs) | Move last to root, sift down, return old root | |
heapreplace(xs, v) | Pop then push, one sift down | |
heappushpop(xs, v) | Push then pop, often no sift at all | |
nlargest(k, xs) | Top k with a size-k heap |
Cheat sheet
Costs and a mnemonic
| Operation | Time | Extra space | Use case |
|---|---|---|---|
| Sift down (once) | loop, recursive | Pop, heap sort, build-heap | |
| Sift up (once) | Push, priority queue insert | ||
| Build heap, bottom up | Initial construction | ||
| Build heap, n inserts | Values arrive one by one | ||
| Peek the root | Max or min lookup |
- 1BottomStart at the last parent or the new leaf
- 2Up or downPick the direction
- 3Big or littleCompare with parent or children
- 4BumpSwap if the rule is broken
- 5LoopRepeat one level on
- 6EndStop when no swap is needed
Recap
Key takeaways
Key points
- Sift down sinks a too-small value below its larger child; sift up lifts a too-big value above its parent. Each is .
- Sift down assumes both subtrees are already heaps; that is why build-heap runs backwards.
- Build-heap: sift down every parent from to 0.
- Build-heap is because work is ; building with inserts is .
- Sift down pays height, sift up pays depth: most nodes are short but deep.
heapq.heapifyis the min-heap build; negate values for a max-heap.