Data Structures · Visualization
Heap Construction: Introduction
Heap Construction
A heap is an array pretending to be a nearly-complete binary tree: children of index i live at 2i+1 and 2i+2. Time: O(n) bottom-up vs O(n log n) repeated insert. Space: O(1) extra — built in place.
Big-O: Bottom-up build O(n); decrease-key O(log n).
Heap Construction: Introduction
Heap ConstructionA heap is an array pretending to be a nearly-complete binary tree: children of index i live at 2i+1 and 2i+2. Inserting one by one costs O(n log n), but building from a full array works bottom-up — small subtrees are already heaps, so each sift-down travels only a short distance, for O(n) total.
How Heap Construction: Introduction Works
- Lay the values out as-is; index math gives the tree shape for free.
- Start from the last parent (index n/2 − 1) and move backwards.
- Sift each node down: swap with the larger child (max-heap) until order holds.
- When the root is sifted, the whole array is a valid heap.
Heap Construction: Introduction Worked Example
Input: Build a max-heap from [4, 10, 3, 5, 1]
- Last parent is index 1 (10): children 5, 1 — already ordered.
- Index 0 (4): larger child is 10 → swap → [10, 4, 3, 5, 1].
- Node 4 at index 1: larger child 5 → swap → [10, 5, 3, 4, 1].
- Root done: valid max-heap in 2 swaps.
Output: Max-heap: [10, 5, 3, 4, 1]
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: intro on [4, 10, 3, 5, 1]Heap Construction: Introduction Time & Space Complexity
When to Use Heap Construction: Introduction
- Heap-sort's first pass and priority-queue bulk loading
- Seeding schedulers with a whole batch of jobs at once
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.