Sub topic 14
Variants: Bottom-Up Heap Sort and d-ary Heaps
This chapter assumes you already know the standard sift_down, build_max_heap, and heap_sort functions from earlier chapters. It also assumes you can count comparisons in a loop and read logarithms in different bases. Two variants keep heap sort's O(n log n) worst case and O(1) extra space but change the constant factors. Bottom-up heap sort reduces the number of comparisons. d-ary heaps reduce the height of the tree.
Where Standard Sift-Down Spends Its Comparisons
During the extraction phase, each step swaps the root with the last heap element and sifts that element down. On each level, standard sift-down makes two comparisons:
- It compares the left child with the right child to find the larger one.
- It compares the larger child with the element being sifted.
The element being sifted came from the bottom of the heap, so it is usually small. It almost always sinks all the way back to the leaf level or close to it. Because of that, the second comparison almost always says "keep going," and the work spent on it is mostly wasted. Over n extractions this gives about 2n log₂ n comparisons.
Bottom-Up Heap Sort
Bottom-up heap sort is usually credited to Floyd's observation and Wegener's analysis. It relies on that wasted comparison. The method skips the "should I stop?" test on the way down. It walks to a leaf first and then backs up to find where the element belongs.
The Three Phases
- Leaf search. Start at the root and repeatedly move to the larger child until you reach a leaf. This costs one comparison per level. The path you follow is the special path: the chain of larger children.
- Climb. Move up the special path from the leaf until you reach a node whose value is at least the sifted element. This usually takes only a step or two, because the sifted element is small.
- Shift. Put the sifted element at that node. Then move every element above it on the path up one level, toward the root.
Implementation
def leaf_search(a, start, end):
# Follow larger children from start down to a leaf; return its index.
j = start
while True:
child = 2 * j + 1
if child >= end:
return j
if child + 1 < end and a[child + 1] > a[child]:
child += 1
j = child
def sift_down_bottom_up(a, start, end):
j = leaf_search(a, start, end)
# Climb until we find a node at least as large as the sifted element.
while a[start] > a[j]:
j = (j - 1) // 2
# Place a[start] at j, then rotate the path values up by one level.
x = a[j]
a[j] = a[start]
while j > start:
p = (j - 1) // 2
a[p], x = x, a[p]
j = p
def bottom_up_heap_sort(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down_bottom_up(a, start, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_bottom_up(a, 0, end)
data = [5, 2, 9, 1, 7, 3, 8, 6, 4]
bottom_up_heap_sort(data)
print(data) # [1, 2, 3, 4, 5, 6, 7, 8, 9]The climb loop always stops. When j reaches start, the test a[start] > a[start] is false. The shift loop does a rotation: the element originally at start ends up at j, and each value on the path from j up to start moves one level higher. The node at j is at least as large as the sifted element. Every node on the path above it was the larger child of its parent, so the heap property still holds after the rotation.
Measuring the Savings
You can count comparisons by wrapping the values in a class that increments a counter on every comparison:
import random
class Counted:
count = 0
def __init__(self, v):
self.v = v
def __lt__(self, other):
Counted.count += 1
return self.v < other.v
def __gt__(self, other):
Counted.count += 1
return self.v > other.v
def __ge__(self, other):
Counted.count += 1
return self.v >= other.v
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
def heap_sort(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(a, start, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
def leaf_search(a, start, end):
j = start
while True:
child = 2 * j + 1
if child >= end:
return j
if child + 1 < end and a[child + 1] > a[child]:
child += 1
j = child
def sift_down_bottom_up(a, start, end):
j = leaf_search(a, start, end)
while a[start] > a[j]:
j = (j - 1) // 2
x = a[j]
a[j] = a[start]
while j > start:
p = (j - 1) // 2
a[p], x = x, a[p]
j = p
def bottom_up_heap_sort(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down_bottom_up(a, start, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_bottom_up(a, 0, end)
random.seed(1)
values = [random.random() for _ in range(10000)]
for name, sort in [("standard", heap_sort), ("bottom-up", bottom_up_heap_sort)]:
items = [Counted(v) for v in values]
Counted.count = 0
sort(items)
assert all(items[i].v <= items[i + 1].v for i in range(len(items) - 1))
print(name, Counted.count)The bottom-up count should be well below the standard count. The analysis gives about n log₂ n + O(n) comparisons for the bottom-up method and about 2n log₂ n for the standard one, so the bottom-up figure should come out at a bit more than half. The exact numbers depend on the input.
Trade-offs and Gotchas
| Aspect | Standard sift-down | Bottom-up sift-down |
|---|---|---|
| Comparisons per extraction | about 2 log₂ n | about log₂ n + small climb |
| Element moves | one swap per level | one move per level, plus the rotation |
| Code complexity | one loop | three loops |
| Best when | comparisons are cheap (ints) | comparisons are expensive (strings, tuples, key functions) |
- The gain depends on the element being small. During extraction, the sifted element comes from the bottom of the heap, so the climb is short. If you use bottom-up sifting for an element that usually belongs near the top, the climb can cost as much as the descent, and you lose the advantage.
- Integer sorts may not get faster. Comparing two machine integers costs about the same as a branch. The extra loops can cancel the savings. Measure on your own data before you switch.
- It is still unstable. The extra ordering logic does nothing to preserve the order of equal keys.
d-ary Heaps
A d-ary heap is a complete tree in which every node has up to d children instead of 2. It is stored in an array the same way as a binary heap, with different index formulas:
- children of i:
d*i + 1throughd*i + d - parent of i:
(i - 1) // d
With d = 2 these are the binary heap formulas you already know.
Implementation
def sift_down_d(a, start, end, d):
root = start
while True:
first = d * root + 1
if first >= end:
break
best = first
for c in range(first + 1, min(first + d, end)):
if a[c] > a[best]:
best = c
if a[root] >= a[best]:
break
a[root], a[best] = a[best], a[root]
root = best
def heap_sort_d(a, d=4):
if d < 2:
raise ValueError("d must be at least 2")
n = len(a)
# The last non-leaf node is the parent of index n - 1.
for start in range((n - 2) // d, -1, -1):
sift_down_d(a, start, n, d)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_d(a, 0, end, d)
for d in (2, 3, 4, 8):
data = [5, 2, 9, 1, 7, 3, 8, 6, 4, 0]
heap_sort_d(data, d)
print(d, data) # each line ends with [0, 1, 2, ..., 9]A common bug is reusing the binary rule for the last non-leaf, n // 2 - 1. For d > 2 that starting point is too high. It still gives correct results, but it wastes calls on leaves. The exact value is (n - 2) // d. For n = 0 or 1 it evaluates to −1, so the build loop correctly does nothing.
Comparisons Versus Height
The tree height is about log_d n. At each level, sift-down makes d − 1 comparisons among the children and one more against the parent, which is d comparisons in total. Using log₂ n as the unit:
| d | Comparisons per level | Levels (× log₂ n) | Comparisons (× log₂ n) | Swaps (× log₂ n) |
|---|---|---|---|---|
| 2 | 2 | 1.00 | 2.00 | 1.00 |
| 3 | 3 | 0.63 | 1.89 | 0.63 |
| 4 | 4 | 0.50 | 2.00 | 0.50 |
| 8 | 8 | 0.33 | 2.67 | 0.33 |
The table shows what you trade by raising d:
- Comparisons are lowest near d = 3 and grow again as d increases.
- Swaps and levels keep falling as d grows, because the tree gets shallower.
- Cache behavior improves for moderate d. The d children of a node sit next to each other in the array, so scanning them reads one or two cache lines. A binary heap instead jumps to a far-away index at every level. With d = 4 and 8-byte elements, the four children often share one 64-byte line.
Choosing d
- For heap sort on large arrays of small keys, try d = 4. You get half the levels and the same comparison count as d = 2, plus better memory locality. Benchmark it, because the gain depends on the hardware.
- When comparisons dominate the cost, d = 2 with bottom-up sifting usually wins. Wide nodes add comparisons, and that is the resource you are trying to save.
- d-ary heaps help most in priority queues where inserts and decrease-key operations outnumber pops, as in Dijkstra's algorithm. Sift-up costs only one comparison per level, and a shallower tree makes it cheaper. Heap sort performs no sift-ups, so it gets a smaller share of this benefit.
Combining the Two
The variants are independent. In a bottom-up d-ary heap, the leaf search costs d − 1 comparisons per level. The climb back up costs one comparison per step, and the step count is usually small. The total is about (d − 1) log_d n comparisons. For d = 2 this matches plain bottom-up sifting. For d = 4 it is about 1.5 log₂ n with half the levels. In practice the combination is rarely worth the extra code unless profiling shows that heap operations are a bottleneck.
Exercise
In bottom-up sift-down, the climb loop is while a[start] > a[j]. Why can the loop never move j above start, and what happens if a[start] is already at least as large as every element on the special path?
Show answer
When j equals start, the test a[start] > a[start] is false, so the loop stops there at the latest. If a[start] is at least as large as every path element, the climb goes all the way back to start. The placement step writes a[start] onto itself, and the shift loop does not run because j > start is false. The heap is unchanged, which is correct, but the leaf search cost about log n comparisons that the standard version would have avoided with a single early check.
Exercise
For a 5-ary heap stored in a zero-indexed array of 23 elements, give the children of index 2, the parent of index 17, and the index of the last non-leaf node.
Show answer
The children of index 2 are 52+1 = 11 through 52+5 = 15. The parent of index 17 is (17-1)//5 = 3. The last non-leaf node is (23-2)//5 = 4. Its first child, 21, is less than 23, while index 5 would have its first child at 26, which is past the end of the array.
Exercise
You need to sort 10 million records by a key function that does an expensive Unicode collation on strings. You must use a heap-based sort. Should you use d = 4 with standard sift-down, or d = 2 with bottom-up sift-down? Justify your choice with comparison counts.
Show answer
Use d = 2 with bottom-up sift-down. Cost is dominated by comparisons. Bottom-up binary sifting needs about 1 × log2 n comparisons per extraction, while a standard 4-ary heap needs about 2 × log2 n. The 4-ary heap's advantages are fewer levels and better cache locality, which matter little when each comparison is far more expensive than a memory access.