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 . 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 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 swaps with the larger child three times and comes to rest at a leaf.
The procedure
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 changedThe 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.
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:
#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 and are max-heaps, then after
SIFT-DOWN(a, i, size)the subtree rooted at 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 the hole, and write for the value that started at the original ; 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 . 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 holds a value . Because the child's subtree is a heap, 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, sits at the old hole: it is at least both of its children (the other child and ), and the parent of the old hole was at least everything in the old hole's subtree, which includes . The only pairs that may now be broken are those between the new hole and its children, and the new hole's parent holds , which was the maximum of 's subtree. The invariant holds again.
- Termination. The loop returns when 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 down to a leaf ([3, 2, 7, 4, 5, 6, 1]), and the result is still not a heap, because and . 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 , sift-down makes at most swaps and at most comparisons: , which is at the root by the height fact of the previous lesson.
The recursive formulation is often analysed with the recurrence , 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 and this is case 2, : 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.
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 : 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 ?
- The whole array must already be a max-heap
- The subtrees rooted at the children of must be max-heaps
- must be the largest value in its subtree
- The array must be sorted
Why does sift-down swap with the **larger** child rather than either child?
- It is only a convention
- So that the value moved up is at least the other child, keeping the property at the hole's old position
- To make the procedure stable
- To use fewer comparisons
At most how many key comparisons does sift-down make when started at a node of height ?