TExcelTAD
Home › Sorting & Order Statistics › Sift-Down and Why It Works

Sift-Down and Why It Works

Every heap algorithm in this course is built from one repair operation. Sift-down (often called heapify or max-heapify) takes a node whose two subtrees are already max-heaps but whose own value may be too small, and lets that value sink until the whole subtree is a max-heap again. It touches one root-to-leaf path, so it costs O(lg⁡n)O(\lg n). This lesson states exactly what sift-down assumes, proves that it delivers, and counts its comparisons.

The array layout and the heap property are from Binary Heaps and the Heap Property.

Watching it

The array [3, 15, 12, 9, 11, 4, 7, 2, 8, 5] is a max-heap everywhere except at the root: both subtrees of position 0 are heaps, but 33 is smaller than its children. The animation runs heapsort, and on this input its heap-building phase consists of exactly one sift-down from the root. Watch the frames up to "Max-heap built": the 33 swaps with the larger child three times and comes to rest at a leaf.

The procedure

text
SIFT-DOWN(a, i, size)           // a[0:size] is the heap; subtrees of i are max-heaps
1  loop
2      l = 2i + 1,  r = 2i + 2
3      largest = i
4      if l < size and a[l] > a[largest]:  largest = l
5      if r < size and a[r] > a[largest]:  largest = r
6      if largest == i:  return            // a[i] is at least both children
7      swap a[i] and a[largest]
8      i = largest                         // continue in the subtree that changed

The parameter size lets the same procedure work on a prefix of the array, which heapsort needs. Many textbooks write sift-down recursively; the loop version is the same algorithm with the tail call turned into a jump, and it needs no stack.

python · try it yourself
def sift_down(a, i, size, trace=False):
    while True:
        l, r = 2 * i + 1, 2 * i + 2
        largest = i
        if l < size and a[l] > a[largest]:
            largest = l
        if r < size and a[r] > a[largest]:
            largest = r
        if largest == i:
            return
        if trace:
            print(f"  {a[largest]} > {a[i]}: swap positions {i} and {largest}")
        a[i], a[largest] = a[largest], a[i]
        i = largest

a = [3, 15, 12, 9, 11, 4, 7, 2, 8, 5]
print("before:", a)
sift_down(a, 0, len(a), trace=True)
print("after: ", a)
before: [3, 15, 12, 9, 11, 4, 7, 2, 8, 5]
  15 > 3: swap positions 0 and 1
  11 > 3: swap positions 1 and 4
  5 > 3: swap positions 4 and 9
after:  [15, 11, 12, 9, 5, 4, 7, 2, 8, 3]

The three swaps are the three "Swap parent and child" frames of the animation, and the result is the array shown at "Max-heap built".

In C++

The same procedure on a std::vector<int>, with the same trace:

cpp · try it yourself
#include <cstdio>
#include <utility>
#include <vector>

void sift_down(std::vector<int>& a, int i, int size) {
    for (;;) {
        int l = 2 * i + 1, r = 2 * i + 2, largest = i;
        if (l < size && a[l] > a[largest]) largest = l;
        if (r < size && a[r] > a[largest]) largest = r;
        if (largest == i) return;
        std::printf("  %d > %d: swap positions %d and %d\n", a[largest], a[i], i, largest);
        std::swap(a[i], a[largest]);
        i = largest;
    }
}

int main() {
    std::vector<int> a = {3, 15, 12, 9, 11, 4, 7, 2, 8, 5};
    sift_down(a, 0, static_cast<int>(a.size()));
    std::printf("after:");
    for (int x : a) std::printf(" %d", x);
    std::printf("\n");
}
  15 > 3: swap positions 0 and 1
  11 > 3: swap positions 1 and 4
  5 > 3: swap positions 4 and 9
after: 15 11 12 9 5 4 7 2 8 3

Correctness

Claim. If the subtrees rooted at left⁡(i)\operatorname{left}(i) and right⁡(i)\operatorname{right}(i) are max-heaps, then after SIFT-DOWN(a, i, size) the subtree rooted at ii is a max-heap holding the same values as before.

The values are only ever swapped, so the second half is immediate. For the first half, use a loop invariant on the loop of lines 1 to 8. Call the position currently held in the variable ii the hole, and write xx for the value that started at the original ii; that value is always the one at the hole.

Invariant. At the start of each iteration, the subtree rooted at the original position satisfies the heap property at every parent-child pair, except possibly the pairs between the hole and its children. Moreover, if the hole has a parent, that parent's value is at least every value in the hole's subtree.

  • Initialization. The hole is the original ii. Its two subtrees are heaps by assumption, so every pair below the hole is fine, and the hole has no parent inside this subtree. The invariant holds.
  • Maintenance. Suppose the hole is not done, so its larger child cc holds a value y>xy > x. Because the child's subtree is a heap, yy is the largest value in that subtree, and it is also larger than the other child and its subtree (lines 4 and 5 picked the maximum). After the swap, yy sits at the old hole: it is at least both of its children (the other child and xx), and the parent of the old hole was at least everything in the old hole's subtree, which includes yy. The only pairs that may now be broken are those between the new hole cc and its children, and the new hole's parent holds yy, which was the maximum of cc's subtree. The invariant holds again.
  • Termination. The loop returns when xx is at least both children of the hole (or the hole is a leaf). Then the excepted pairs are fine too, so the whole subtree is a heap.

The loop terminates because the hole moves one level down on every swap: its height is a variant that strictly decreases and cannot go below 0.

Note: The precondition matters. Sift-down repairs one misplaced value at the top of two heaps. It does not turn an arbitrary array into a heap: on [1, 2, 3, 4, 5, 6, 7] a sift-down from the root moves the 11 down to a leaf ([3, 2, 7, 4, 5, 6, 1]), and the result is still not a heap, because 2<42 < 4 and 2<52 < 5. Building a heap needs many sift-downs in the right order, which is the next lesson.

Cost

Each loop iteration does at most 2 key comparisons (lines 4 and 5) and one swap, and the hole moves down a level each time. The last iteration, the one that returns, compares only if the hole still has a child, and then the hole is at least one level above the bottom of the subtree. So starting from a node of height hh, sift-down makes at most hh swaps and at most 2h2h comparisons: O(h)O(h), which is O(lg⁡n)O(\lg n) at the root by the height fact of the previous lesson.

The recursive formulation is often analysed with the recurrence T(n)≤T(2n/3)+Θ(1)T(n) \le T(2n/3) + \Theta(1), because a child's subtree holds at most about two thirds of the nodes (the worst case is a bottom level exactly half full, so the left subtree has one more full level than the right). By the master theorem with a=1a = 1 and b=3/2b = 3/2 this is case 2, T(n)=O(lg⁡n)T(n) = O(\lg n): the same answer by a longer road. The height argument is more direct.

The program below tests the claim on random inputs: it builds a max-heap by repeated pushes, replaces the root with a random value (so both subtrees are still heaps), sifts down, and checks the heap property, the multiset of values and the comparison bound.

python · try it yourself
import math, random
from collections import Counter

def sift_down_counted(a, i, size):
    comparisons = swaps = 0
    while True:
        l, r = 2 * i + 1, 2 * i + 2
        largest = i
        if l < size:
            comparisons += 1
            if a[l] > a[largest]: largest = l
        if r < size:
            comparisons += 1
            if a[r] > a[largest]: largest = r
        if largest == i:
            return comparisons, swaps
        a[i], a[largest] = a[largest], a[i]
        swaps += 1
        i = largest

def push(heap, x):                      # max-heap push (sift up)
    heap.append(x)
    i = len(heap) - 1
    while i > 0 and heap[(i - 1) // 2] < heap[i]:
        heap[(i - 1) // 2], heap[i] = heap[i], heap[(i - 1) // 2]
        i = (i - 1) // 2

def is_max_heap(a):
    return all(a[(i - 1) // 2] >= a[i] for i in range(1, len(a)))

rng = random.Random(5)
worst = {}
for trial in range(2000):
    n = rng.randint(1, 60)
    heap = []
    for _ in range(n):
        push(heap, rng.randint(0, 99))
    heap[0] = rng.randint(0, 99)        # spoil only the root
    before = Counter(heap)
    c, s = sift_down_counted(heap, 0, n)
    assert is_max_heap(heap) and Counter(heap) == before
    h = math.floor(math.log2(n))
    assert s <= h and c <= 2 * h
    worst[h] = max(worst.get(h, 0), c)
print("2000 random repairs: heap property and values preserved")
for h in sorted(worst):
    print(f"height {h}: most comparisons seen {worst[h]}, bound 2h = {2 * h}")
2000 random repairs: heap property and values preserved
height 0: most comparisons seen 0, bound 2h = 0
height 1: most comparisons seen 2, bound 2h = 2
height 2: most comparisons seen 4, bound 2h = 4
height 3: most comparisons seen 6, bound 2h = 6
height 4: most comparisons seen 8, bound 2h = 8
height 5: most comparisons seen 10, bound 2h = 10

Every height reaches the bound 2h2h: a value that sinks all the way down through nodes with two children costs exactly two comparisons per level, and the leaf where it stops costs none.

Test yourself

What must hold before SIFT-DOWN(a, i, size) for it to produce a max-heap at ii?

  1. The whole array must already be a max-heap
  2. The subtrees rooted at the children of ii must be max-heaps
  3. a[i]a[i] must be the largest value in its subtree
  4. The array must be sorted

Why does sift-down swap with the **larger** child rather than either child?

  1. It is only a convention
  2. So that the value moved up is at least the other child, keeping the property at the hole's old position
  3. To make the procedure stable
  4. To use fewer comparisons

At most how many key comparisons does sift-down make when started at a node of height hh?

  1. hh
  2. 2h2h
  3. h2h^2
  4. lg⁡h\lg h