AlgoFrames

Building a heap in O(n)

Heapify builds a heap from an array in O(n) by sifting down from the last internal node backward. Most nodes are near the bottom and move little.

Before you start: Binary heaps: array layout, sift up, sift down.

The idea

Ten values sit in an array in no order. We want a max-heap: every parent at least as large as its children.

Pushing the values one by one works but costs O(n log n). This lesson rearranges the array in place in O(n).

Intuition

Indices 5 to 9 have no children. A single node is already a heap, so half the array needs no work.

The last node with a child sits at index n / 2 - 1. Here n = 10, so the work starts at index 4.

Index 4 has its child at 2 · 4 + 1 = 9, the last cell. Index 5 would need a child at 11, which does not exist.

Sift down index 4, then 3, 2, 1 and 0. Each parent is sifted after both its subtrees are heaps.

Sift down only repairs one value on top of two valid heaps. Going backward makes that true at every step.

Complexity

Only the root can sink 3 levels. Eight leaves sink 0, so 15 nodes need at most 11 swaps in total.

Half the nodes are leaves, a quarter sink at most 1 level, an eighth at most 2. The sum stays below n.

Build-heap makes fewer than n swaps, so it runs in O(n). Pushing one by one grows like n log n.

For 128 values the worst case is 127 swaps for build-heap and 649 for 128 pushes. It uses O(1) extra memory.

Pitfalls

Sifting from index 0 forward fails. Here 3 ends at the root above 7, because 7 rose after the root was done.

Starting the loop at n - 1 still works, but the first half of the loop sifts leaves and does nothing.

Variations

Flip the comparison and the same loop builds a min-heap. Python's heapq.heapify does this in O(n).

Heap sort begins with build-heap. Then it swaps the root 16 to the last cell and repeats.

Code

Pseudocode

build_heap(a)
  n ← length of a
  for i from n / 2 - 1 down to 0
    sift_down(a, i, n)

sift_down(a, i, n)
  loop
    c ← the larger child of i
    if c does not exist or a[i] ≥ a[c]: stop
    swap a[i] and a[c]
    i ← c

Python

def build_heap(a):
    n = len(a)
    for i in range(n // 2 - 1, -1, -1):
        sift_down(a, i, n)

def sift_down(a, i, n):
    while True:
        c = 2 * i + 1
        if c >= n: return
        if c + 1 < n and a[c + 1] > a[c]: c += 1
        if a[i] >= a[c]: return
        a[i], a[c] = a[c], a[i]
        i = c

JavaScript

function buildHeap(a) {
  const n = a.length;
  for (let i = (n >> 1) - 1; i >= 0; i--) {
    siftDown(a, i, n);
  }
}

function siftDown(a, i, n) {
  while (true) {
    let c = 2 * i + 1;
    if (c >= n) return;
    if (c + 1 < n && a[c + 1] > a[c]) c++;
    if (a[i] >= a[c]) return;
    [a[i], a[c]] = [a[c], a[i]];
    i = c;
  }
}

Java

static void buildHeap(int[] a) {
    int n = a.length;
    for (int i = n / 2 - 1; i >= 0; i--) {
        siftDown(a, i, n);
    }
}

static void siftDown(int[] a, int i, int n) {
    while (true) {
        int c = 2 * i + 1;
        if (c >= n) return;
        if (c + 1 < n && a[c + 1] > a[c]) c++;
        if (a[i] >= a[c]) return;
        int tmp = a[i]; a[i] = a[c]; a[c] = tmp;
        i = c;
    }
}

Practice problems (6)

Why is build-heap O(n)? Warm-up

Build-heap calls sift down on n / 2 nodes, and one sift down can cost O(log n). Yet the whole build runs in O(n). Pick the reason.

Is it a max-heap? Warm-up

Return true when the array values is a valid max-heap: no value is smaller than one of its children. The children of index i are at 2i + 1 and 2i + 2.

An empty array and a single value are valid max-heaps.

Heapify Standard

Run build-heap on [3, 9, 2, 1, 4, 5, 8] to make a max-heap. Sift down index 2, then 1, then 0.

Predict the first swap, then arrange the array as it looks when build-heap finishes.

Count sift steps Standard

Build-heap turns [5, 3, 8, 4, 1, 7, 2, 9, 6] into a max-heap. One sift step is one swap of a value with its larger child.

Count the swaps as the trace plays.

Sift down one index Standard

In values, the subtrees below index i are already max-heaps, but values[i] may be too small. Sift it down: while it is smaller than its larger child, swap the two. When both children are equal, use the left child.

Return the array after the sift.

Implement build-heap Challenge

Rearrange values in place into a max-heap and return it. Every value must be at least as large as its children at 2i + 1 and 2i + 2.

Use the bottom-up method: sift down every parent, from the last one back to index 0. Any valid max-heap of the same values is accepted.

Related topics

Next on the path: Heap sort