Sub topic 15
d-ary heaps and other heap variants
This chapter assumes you know the binary heap from the earlier chapters: the heap property, the array layout, sift up and sift down, and the idea of decrease-key. You should also be comfortable with O(log n) reasoning.
From two children to d children
A binary heap gives each node at most 2 children. A d-ary heap gives each node at most d children. It keeps the same complete-tree shape and the same heap property, and it still lives in one array. Only the index arithmetic changes. For a node at index i:
- The parent is at
(i - 1) // d. - The children are at
d * i + 1throughd * i + d.
With d = 2 these formulas reduce to the binary rules.
What changes in the cost
A larger d makes the tree shallower. Its height is about log base d of n. For n = 1,000,000, a binary heap is about 20 levels deep and a 4-ary heap is about 10.
| Operation | Binary heap | d-ary heap |
|---|---|---|
| Sift up (push, decrease-key) | up to log2 n comparisons | up to log_d n comparisons |
| Sift down (pop) | about 2 log2 n comparisons | about d · log_d n comparisons |
| Peek | O(1) | O(1) |
Sift up gets cheaper as d grows. Sift down gets more expensive, because each level requires scanning all d children to find the smallest. A d-ary heap pays off when sift up is common, as in decrease-key-heavy workloads. Dijkstra on a dense graph is an example, because it can perform many more decrease-key operations than pops. Values like d = 4 also tend to work well in practice, because the children sit next to each other in memory and one cache line can cover several of them.
A d-ary heap in Python
class DaryMinHeap:
def __init__(self, d=4):
if d < 2:
raise ValueError("d must be at least 2")
self._d = d
self._a = []
def __len__(self):
return len(self._a)
def push(self, x):
a, d = self._a, self._d
a.append(x)
i = len(a) - 1
while i > 0:
parent = (i - 1) // d
if a[parent] <= a[i]:
break
a[parent], a[i] = a[i], a[parent]
i = parent
def pop(self):
a, d = self._a, self._d
if not a:
raise IndexError("pop from empty heap")
top = a[0]
last = a.pop()
if a:
a[0] = last
i, n = 0, len(a)
while True:
first = d * i + 1
if first >= n:
break
end = min(first + d, n)
child = min(range(first, end), key=a.__getitem__)
if a[i] <= a[child]:
break
a[i], a[child] = a[child], a[i]
i = child
return top
h = DaryMinHeap(d=4)
for x in [9, 4, 7, 1, 8, 2, 6]:
h.push(x)
print([h.pop() for _ in range(len(h))]) # [1, 2, 4, 6, 7, 8, 9]The only change from the binary version is the loop that picks the smallest of up to d children.
Other heap variants
Some variants trade simplicity for better bounds on specific operations.
| Variant | Strength | Cost |
|---|---|---|
| Binomial heap | Merging two heaps in O(log n) | More complex than an array heap |
| Leftist and skew heaps | Simple pointer-based merging | Pointer chasing, poor cache use |
| Pairing heap | Fast in practice, simple decrease-key | Decrease-key bound is not fully settled |
| Fibonacci heap | Amortized O(1) decrease-key and insert | Large constants, complex code |
A Fibonacci heap improves Dijkstra's asymptotic bound to O(E + V log V). The improvement rarely shows up in measured running time, because the constant factors are high.
Exercise
In a 3-ary heap stored in an array, which indexes hold the children of the node at index 4, and what is the parent of index 14?
Show answer
The children of index 4 are 3·4+1 = 13, 14 and 15. The parent of index 14 is (14 − 1) // 3 = 4.