Sub topic 4
Sift-Down: Restoring Order One Subtree at a Time
This chapter assumes you can already map a tree node at index i to its children at 2*i + 1 and 2*i + 2. It also assumes you know the max-heap property: every parent is at least as large as its children. You should be comfortable reading Python loops and reasoning in Big-O terms.
Sift-down is the one operation heap sort depends on. Building the heap is a loop of sift-downs. Each step of the sort also ends with a sift-down. If you understand exactly what sift-down promises and what it requires, the rest of heap sort follows quickly.
The Problem Sift-Down Solves
Picture a subtree in which everything is a valid max-heap except the root. The root holds a value that may be smaller than one or both of its children. Both child subtrees are already valid heaps on their own.
This situation comes up in two places:
- During heap construction, you process nodes from the bottom up. When you reach a node, both of its subtrees have already been fixed.
- During sorting, you swap the maximum out of the root and put the last leaf in its place. The new root is probably small, but the rest of the tree is untouched and still a heap.
Sift-down repairs that one broken spot. It moves the misplaced value down the tree until the heap property holds again.
The precondition
Sift-down does not turn an arbitrary subtree into a heap. It assumes:
- The left subtree of
startis a valid max-heap. - The right subtree of
startis a valid max-heap.
Only the value at start may be out of place. If either subtree is broken, sift-down can finish without error and still leave the heap property violated. The exercises at the end include a case like this.
The Algorithm
At each step, sift-down compares the current node with its larger child:
- If the node is at least as large as that child, the heap property holds here. Since everything below is already a heap, you can stop.
- Otherwise, swap the node with the larger child and continue from the child's position.
- If the node has no children inside the heap, it is a leaf, and you stop.
You must pick the larger child. Suppose you swapped with the smaller one. The smaller child would become the parent of the larger one, and that breaks the heap property right where you just stood.
The Implementation
def sift_down(a, start, end):
# Restore the max-heap property for the subtree rooted at start,
# considering only a[0:end].
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and a[child + 1] > a[child]:
child += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
a = [2, 9, 8, 7, 5, 6, 4]
sift_down(a, 0, len(a))
print(a) # [9, 7, 8, 2, 5, 6, 4]Why there is an `end` parameter
The end argument marks where the heap stops. Only indices 0 through end - 1 count as part of the heap. When you build a heap, end is the full array length. During the sort, the back of the array holds elements that are already in their final sorted positions, and the heap shrinks by one with each step. Sift-down must not look at those positions.
def sift_down(a, start, end):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and a[child + 1] > a[child]:
child += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
a = [1, 5, 3, 9]
sift_down(a, 0, 3) # heap is a[0:3]; the 9 at index 3 is off-limits
print(a) # [5, 1, 3, 9]Index 1 would have a left child at index 3. Because 3 >= end, sift-down treats index 1 as a leaf, and the 9 stays where it is.
Tracing a Sift-Down
Take a = [2, 9, 8, 7, 5, 6, 4]. The root value 2 is out of place. The subtree at index 1 (9 with children 7 and 5) and the subtree at index 2 (8 with children 6 and 4) are both valid heaps, so the precondition holds.
| Step | root | children (index: value) | larger child | action | array after |
|---|---|---|---|---|---|
| 1 | 0 | 1: 9, 2: 8 | 1 (9) | 2 < 9, swap | [9, 2, 8, 7, 5, 6, 4] |
| 2 | 1 | 3: 7, 4: 5 | 3 (7) | 2 < 7, swap | [9, 7, 8, 2, 5, 6, 4] |
| 3 | 3 | 7 is not < 7 | none | leaf, stop | [9, 7, 8, 2, 5, 6, 4] |
The value 2 sank two levels. It followed the path of larger children, and those children moved up one level each. The right subtree rooted at 8 was never touched. Sift-down only visits a single root-to-leaf path.
Why It Works
Here is the invariant: at the start of each loop iteration, the only possible heap violation in the subtree is between a[root] and its children.
- At the start, this is just the precondition.
- When you swap
a[root]with its larger childc, the new value atrootisa[c]. That value is at least as large as the other child, because you chose the larger one. It is also at least as large as everything belowc, because the subtree atcwas a heap. So the positionrootis now correct. - The old root value now sits at
c. The subtrees belowcare unchanged heaps. The invariant holds again, one level lower. - The loop stops either because
a[root] >= a[child], which means no violation is left, or becauserootis a leaf, which has no children to violate.
Each iteration moves root down one level, so the loop always ends.
Cost
A heap with n elements has height floor(log2 n). Sift-down does constant work per level: at most two comparisons and one swap. Starting from index start, it runs at most as many iterations as the height of that node's subtree.
| Measure | Worst case | Best case |
|---|---|---|
| Comparisons | about 2 × height | 1 or 2 (stop immediately) |
| Swaps | height | 0 |
| Time from root | O(log n) | O(1) |
| Extra space | O(1) | O(1) |
The phrase "height of the subtree at start" matters. Nodes near the bottom have short subtrees, so sift-down on them is cheap. A later chapter uses this fact to show that building a heap takes O(n) time instead of O(n log n).
Common Mistakes
Swapping with the wrong child
If you compare the root with only the left child, or swap with whichever child comes first, you can promote a smaller value above a larger sibling. Always choose the larger child first, then compare it with the root.
Dropping the `child + 1 < end` check
Without this check, a[child + 1] can raise IndexError at the end of a list. The worse case raises no error at all. During heap sort, child + 1 may point into the sorted region at the back of the array. Sift-down then pulls a large, already-placed element back into the heap and silently corrupts the output.
Using `len(a)` instead of `end`
This mistake has the same effect as the previous one. The function looks correct when you test it on its own and only fails inside heap sort. Always bound child indices by end.
Expecting it to heapify anything
Calling sift_down(a, 0, n) on an unordered array does not produce a heap. It fixes one path. Building a heap needs many calls in the right order, which is the topic of the next chapter.
`>=` versus `>` in the stop test
Both are correct. With >=, the loop stops when the root equals its larger child, which avoids a swap that achieves nothing. With >, the loop does extra swaps among equal values. That is harmless for correctness, but it is wasted work.
A Variant: Moving a Hole Instead of Swapping
Each swap writes to two array positions. You can halve the writes by holding the sinking value aside. Shift larger children up into the gap, and write the held value once at the end:
def sift_down_hole(a, start, end):
item = a[start]
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and a[child + 1] > a[child]:
child += 1
if item >= a[child]:
break
a[root] = a[child] # move child up into the hole
root = child
a[root] = item
a = [2, 9, 8, 7, 5, 6, 4]
sift_down_hole(a, 0, len(a))
print(a) # [9, 7, 8, 2, 5, 6, 4]The comparisons and the result are identical. The only difference is fewer memory writes, which can matter when elements are large records. Python's own heapq module uses this hole-moving approach.
Exercises
Exercise
Run sift_down(a, 0, 6) on a = [3, 8, 7, 1, 2, 6] by hand. First check that the precondition holds, then give the final array.
Show answer
Precondition: index 1 (8, children 1 and 2) and index 2 (7, child 6) are both heaps, so it holds. Step 1: the larger child of 3 is 8 at index 1, and 3 < 8, so swap to get [8, 3, 7, 1, 2, 6]. Step 2: at index 1, the children are 1 and 2, so the larger is 2 at index 4. Since 3 >= 2, stop. Final array: [8, 3, 7, 1, 2, 6].
Exercise
Call sift_down(a, 0, 4) on a = [1, 2, 3, 4]. What is the result, and is it a valid max-heap? Explain.
Show answer
The children of index 0 are 2 and 3. The larger is 3, so swap to get [3, 2, 1, 4]. Index 2 has its child at 5, which is beyond end, so stop. The result [3, 2, 1, 4] is not a max-heap, because 4 sits below its parent 2. The precondition failed: the subtree at index 1 (2 with child 4) was not a heap, and sift-down never visits that branch.
Exercise
In heap sort, the call is sift_down(a, 0, end) with a sorted suffix a[end:]. Describe what could happen if the right-child check used len(a) instead of end.
Show answer
When child + 1 equals end, the code would treat a[end] as a right child. a[end] is the smallest element of the sorted suffix, but it is at least as large as every element still in the heap. So the code could pick it as the larger child and swap it back into the heap, sending a heap element into the sorted region. The output would be wrong and no error would be raised.
Exercise
What is the maximum number of swaps sift_down(a, 0, n) can perform when n = 100, and why?
Show answer
Six. The height of a complete binary tree with 100 nodes is floor(log2 100) = 6, and each swap moves the value down exactly one level.