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:
Valid max-heap array:
How Floyd's build works
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.
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 = 6buildMaxHeap pseudocode
1buildMaxHeap(array): // O(n) — Floyd's algorithm2 n <- array.size3 last <- floor(n / 2) - 1 // last internal node index4 i <- last5 while i >= 0:6 siftDown(array, i, n)7 i <- i - 189siftDown(array, i, n): // repair heap at index i10 largest <- i11 left <- 2*i + 112 right <- 2*i + 213 if left < n and array[left] > array[largest]: largest <- left14 if right < n and array[right] > array[largest]: largest <- right15 if largest != i:16 swap(array[i], array[largest])17 siftDown(array, largest, n) // recurse down1819// Example: buildMaxHeap([3,9,2,1,5,7,4])20// n=7, last internal = floor(7/2)-1 = 221// 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 swap23// 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
Time complexity
Linear time
Linearithmic time
Logarithmic time
🎯 Quick Check
In Floyd's buildMaxHeap, why do we start from index floor(n/2)-1 instead of index 0?
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).