Data Structures · Visualization
Heap Construction: Build Heap
Heap Construction
Build-heap (heapify) turns the last parent into a sift-down sweep toward the root. Time: O(n) — heights shrink geometrically down the tree. Space: O(1) extra.
Big-O: Bottom-up build O(n); decrease-key O(log n).
Heap Construction: Build Heap
Heap ConstructionBuild-heap (heapify) turns the last parent into a sift-down sweep toward the root. Most nodes sit near the leaves with almost nowhere to fall, so total work sums to linear — the classic proof that this is faster than n inserts. Try it below with your own longer list and watch the swap count stay small.
How Build Heap Works
- Find the last parent at index floor(n/2) − 1.
- For i from there down to 0: sift node i down.
- Sift-down: while a child is larger (max-heap), swap with the largest child.
- Count the swaps — far fewer than n·log n.
Build Heap Worked Example
Input: Build a max-heap from [7, 2, 9, 4, 1, 8]
- Last parent index 2 (9): leaf children, nothing to do.
- Index 1 (2): larger child 4 → swap → [7, 4, 9, 2, 1, 8].
- Node 2 fell to index 3 (leaf) → stop.
- Index 0 (7): larger child 9 → swap → [9, 4, 7, 2, 1, 8]; node 7 at index 2 has leaf children → done.
Output: Max-heap: [9, 4, 7, 2, 1, 8] in 2 swaps
Press ▶ Run to watch it step by step.
def build_heap(a):
for i in range(len(a) // 2 - 1, -1, -1):
sift_down(a, i) # small subtrees first
arr = [7, 2, 9, 4, 1, 8] # O(n) total
# example: build on [7, 2, 9, 4, 1, 8]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Build Heap Time & Space Complexity
When to Use Build Heap
- Turning a database result batch into a top-K structure
- Initialising event simulators with all events known upfront
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.