Sub topic 1
Complete Binary Trees: The Shape Behind a Heap
Prerequisites
This chapter assumes you can write Python functions and loops, use zero-based array indexing, read Big-O notation, and picture a binary tree as nodes with left and right children.
Complete Binary Trees
A complete binary tree fills every level fully, except possibly the last level. The last level fills from left to right with no gaps. Because of this rule, a tree of n nodes always has height about log2(n). Heap sort's speed comes from that bound.
Storing a Tree in an Array
A complete tree has no gaps, so you can store it level by level in a plain array. The tree needs no pointers. Index arithmetic finds any node's parent and children:
def parent(i):
return (i - 1) // 2
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2A common error is mixing these formulas with the one-based versions (i // 2, 2i, 2i + 1). Pick one convention and keep it.
The Max-Heap Property
An array is a max-heap when every node is greater than or equal to its children. This puts the maximum at index 0. You only need to compare each node with its parent:
def is_max_heap(a):
for i in range(1, len(a)):
if a[(i - 1) // 2] < a[i]:
return False
return True
print(is_max_heap([9, 7, 8, 3, 5, 6])) # True
print(is_max_heap([3, 7, 8])) # FalseSift-Down
Sift-down fixes one subtree whose root may be out of place, as long as both child subtrees are already heaps. It swaps the root with its larger child and repeats until the root is at least as large as both children or reaches a leaf. Each swap moves one level down, so it costs O(log n).
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 = [2, 9, 8, 3, 5, 6]
sift_down(a, 0, len(a))
print(a) # [9, 5, 8, 3, 2, 6]The end parameter limits the heap to a[0:end]. Heap sort needs this limit later, when the sorted tail of the array must stay untouched.
Exercise
In a zero-indexed heap, what is the parent index of node 10, and what are the child indices of node 4?
Show answer
The parent is (10 - 1) // 2 = 4. The children of node 4 are 24 + 1 = 9 and 24 + 2 = 10.
Exercise
Is [10, 4, 9, 5, 1] a max-heap? Explain.
Show answer
No. Index 3 holds 5, and its parent at index 1 holds 4. Since 4 < 5, the property fails.