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 Construction

Build-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

  1. Find the last parent at index floor(n/2) − 1.
  2. For i from there down to 0: sift node i down.
  3. Sift-down: while a child is larger (max-heap), swap with the largest child.
  4. 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]

  1. Last parent index 2 (9): leaf children, nothing to do.
  2. Index 1 (2): larger child 4 → swap → [7, 4, 9, 2, 1, 8].
  3. Node 2 fell to index 3 (leaf) → stop.
  4. 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

Try your own input
Heap Construction: Introduction
Bottom-up heapify beats repeated insert: O(n), in place.
7
0
2
1
9
2
4
3
1
4
8
5
Swapping pair
Heap Construction: Introduction
Press ▶ Run to watch it step by step.
Python · Heap Construction in Code
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]
Input: Build a max-heap from [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

TimeO(n) — heights shrink geometrically down the tree
SpaceO(1) extra

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.