Chapter 10 · Trees

Heapify

You have n unsorted elements. Can you arrange them into a valid heap? The naive way (insert one-by-one) takes O(n log n). Floyd's heapify algorithm does it in O(n) — a beautiful insight.

What is heapify?

Heapify turns an arbitrary array into a valid heap in place. Starting from the last non-leaf node and moving back to the root, it sifts each node down until its children are larger (for a min-heap). Surprisingly, this takes O(n) total, not O(n log n), because most nodes are near the bottom and only move a short distance.

function heapify(a) {                       // min-heap, O(n)
  for (let i = (a.length >> 1) - 1; i >= 0; i--) siftDown(a, i);
  return a;
}
function siftDown(a, i) {
  for (;;) {
    let s = i; const l = 2 * i + 1, r = l + 1;
    if (a[l] < a[s]) s = l;
    if (a[r] < a[s]) s = r;
    if (s === i) return;
    [a[i], a[s]] = [a[s], a[i]]; i = s;
  }
}
heapify([5, 3, 8, 1, 2]);   // [1, 2, 8, 3, 5]

Before and after heapify

Original unsorted array:

3
[0]
9
[1]
2
[2]
1
[3]
5
[4]
7
[5]
4
[6]
↓ buildMaxHeap() — O(n) ↓

Valid max-heap array:

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

How Floyd's build works

1 / 3
1

Start from last non-leaf

Leaf nodes (indices n/2 to n-1) are trivially valid heaps of size 1. We only need to fix internal nodes. Start at index floor(n/2) - 1, which is the last node that has at least one child.

1 of 3

Live demo — min-heap operations

Insert values and watch heapify-up bubble them into the correct position. Extract-min removes the root and heapify-down restores the heap.

Min-Heap — parent ≤ children always

min = 1 · size = 6
1531087
root (min)bubble-up pathextracted min
arr:
1
[0]
5
[1]
3
[2]
10
[3]
8
[4]
7
[5]

buildMaxHeap pseudocode

heapify.pseudo
1buildMaxHeap(array): // O(n) — Floyd's algorithm
2 n <- array.size
3 last <- floor(n / 2) - 1 // last internal node index
4 i <- last
5 while i >= 0:
6 siftDown(array, i, n)
7 i <- i - 1
8 
9siftDown(array, i, n): // repair heap at index i
10 largest <- i
11 left <- 2*i + 1
12 right <- 2*i + 2
13 if left < n and array[left] > array[largest]: largest <- left
14 if right < n and array[right] > array[largest]: largest <- right
15 if largest != i:
16 swap(array[i], array[largest])
17 siftDown(array, largest, n) // recurse down
18 
19// Example: buildMaxHeap([3,9,2,1,5,7,4])
20// n=7, last internal = floor(7/2)-1 = 2
21// i=2: siftDown([3,9,2,...], 2) -> swap 2,7 -> [3,9,7,1,5,2,4]
22// i=1: siftDown([3,9,7,...], 1) -> 9 > 3, no swap
23// i=0: siftDown([3,9,7,...], 0) -> swap 3,9 -> [9,3,7,...]
24// siftDown at 1 -> swap 3,5 -> [9,5,7,1,3,2,4] (done)

The O(n) proof intuition

h = 0n/2 nodes, 0 per nodeΣ = 0
h = 1n/4 nodes, 1 swap maxΣ = n/4
h = 2n/8 nodes, 2 swaps maxΣ = n/4
h = 3n/16 nodes, 3 swaps maxΣ = 3n/16
Total work = n/4 + n/4 + 3n/16 + … ≤ 2n = O(n). The geometric series converges.
🔍The key insight
Most nodes live near the bottom and have tiny subtrees. Leaves (half the nodes) do zero work. Nodes at height 1 (a quarter of all nodes) do at most 1 swap. This distribution is why the total converges to O(n) despite each siftDown being O(log n).

Time complexity

buildMaxHeap — Floyd's algorithm (optimal)O(n)

Linear time

build by inserting n elements one-by-one (naive)O(n log n)

Linearithmic time

single siftDown callO(log n)

Logarithmic time

🎯 Quick Check

In Floyd's buildMaxHeap, why do we start from index floor(n/2)-1 instead of index 0?

🧠Heapify powers heap sort
Heap sort uses heapify as step 1: build a max-heap in O(n). Then step 2: repeatedly extract the max (O(log n) each) into a sorted output array. Total: O(n) + O(n log n) = O(n log n) with O(1) extra space. In-place!

Heapify: summary

Key points

  • Leaves (the second half of the array) are already valid heaps, so the loop starts at n/2 − 1.
  • Heap sort = heapify, then repeatedly swap the root to the end and sift down: O(n log n), in place.

Frequently asked questions

›Why is building a heap O(n) and not O(n log n)?

Half the nodes are leaves (no work), a quarter move at most 1 level, an eighth at most 2, and so on. That series sums to O(n).