โ† Back to Heaps

How Heaps Work

Interactive visualization of min-heap insert and extract operations

๐Ÿ”๏ธ Heap Animation

Watch insert, extract, and build heap in action!

Min-Heap: Parent โ‰ค Children

1[0]3[1]5[2]7[3]4[4]8[5]6[6]

๐Ÿ”ข Array Index Formulas

Parent

โŒŠ(i โˆ’ 1) / 2โŒ‹

Left Child

2 ร— i + 1

Right Child

2 ร— i + 2

๐Ÿ‘† Click any node in the tree to see the formulas in action

Array Representation:

1[0]
3[1]
5[2]
7[3]
4[4]
8[5]
6[6]

๐Ÿ”จ Build Heap โ€” Process Order

Start from index โŒŠn/2โŒ‹ โˆ’ 1 = 2 and bubble down each node going left to index 0. Leaves (indices 3โ€“6) are already valid heaps โ€” skip them!

1[0]#3
3[1]#2
5[2]#1
7[3]leaf
4[4]leaf
8[5]leaf
6[6]leaf
Bubble down (#order)Leaf (skipped)
Root (Min)ProcessingComparingSwappingNormal

๐Ÿ“ Time Complexity

OperationTimeSpaceWhy
InsertO(log n)O(1)Bubble up through at most log n levels
Extract MinO(log n)O(1)Bubble down through at most log n levels
Peek (min)O(1)O(1)Min is always at index 0 (root)
Heapify (build)O(n)O(1)Bottom-up โ€” most nodes are leaves and don't move
Insert n itemsO(n log n)O(n)Each of n inserts costs O(log n)
SearchO(n)O(1)Heap is not sorted โ€” must check every element

Why is heapify O(n) and not O(n log n)?

Heapify works bottom-up: it calls bubble_down from the last non-leaf to the root. Most nodes are near the bottom of the tree and move very little:

Leaves (bottom)

n/2 nodes

0 moves

Level above

n/4 nodes

โ‰ค 1 move

Next level

n/8 nodes

โ‰ค 2 moves

Root (top)

1 node

โ‰ค log n moves

Total work: n/4 ยท 1 + n/8 ยท 2 + n/16 ยท 3 + ... โ‰ˆ n (geometric series). Half the nodes do zero work, a quarter do one swap โ€” it adds up to O(n), not O(n log n).