Sub topic 3
The Max-Heap Property
This chapter assumes you already know how a complete binary tree is stored in a zero-indexed array: the parent of index i is (i - 1) // 2, and its children are 2 * i + 1 and 2 * i + 2. It also assumes you can read Python loops and functions and know what O(n) means. Here we add the ordering rule that turns such an array into a heap. Heap sort depends entirely on this rule.
The Rule Itself
An array a of length n is a max-heap when every element other than the root is no larger than its parent:
- For every index
iwith1 <= i < n:a[(i - 1) // 2] >= a[i].
You can state the same rule from the parent's side: every node is greater than or equal to each of its children. The two statements check exactly the same set of parent–child pairs, just from opposite ends.
A min-heap is the mirror image. Every node is less than or equal to its children. Everything in this chapter applies to min-heaps if you flip the comparison. Heap sort in ascending order uses a max-heap, so that is the version we focus on.
Check each edge in the diagram: 9 ≥ 7, 9 ≥ 8, 7 ≥ 3, 7 ≥ 5, 8 ≥ 6. All five pairs pass, so the array is a max-heap.
Why Local Checks Give Global Order
The rule only compares a node with its immediate parent. Yet it guarantees something much stronger. Because >= is transitive, if a[p] >= a[c] and a[c] >= a[g], then a[p] >= a[g]. Chain this along any path from the root downward and you get the following facts:
- The root holds the maximum. Every element sits on some path from the root, and values never increase along that path. Heap sort uses this property. It always knows where the largest remaining element is: at index 0.
- Every root-to-leaf path is non-increasing. Reading
a[0], then a child, then a grandchild, and so on, the values never increase. - Every subtree is itself a max-heap. The rule holds for all pairs, so it holds for the pairs inside any subtree. The root of a subtree is the maximum of that subtree.
- The second largest element is a child of the root. It must be at index 1 or 2. Any deeper position would have a parent that is at least as large, and only the root may be larger.
- Some copy of the minimum sits in a leaf. If an internal node held the minimum, its child would be no larger, so it would also hold the minimum. Follow children down and you reach a leaf. In a zero-indexed heap the leaves are indices
n // 2throughn - 1.
What the Property Does Not Say
The heap property leaves a lot unconstrained. Most beginner bugs come from assuming order that isn't there.
- Siblings are unordered. In the example, the left child 7 is smaller than the right child 8. The opposite would be equally valid.
- Nodes on different branches are unordered. The value 3 at index 3 is smaller than 6 at index 5. Nothing requires that. A deep node in one subtree can be larger than a shallow node in another subtree.
- A heap is not sorted.
[9, 7, 8, 3, 5, 6]is a heap but is not in descending order. A descending array is always a heap, but most heaps are not sorted. - A heap is not a binary search tree. A binary search tree orders left against right (left < node < right). A heap orders parent against child. You cannot search a heap for an arbitrary value in O(log n). You may have to look at every element.
Checking the Property in Code
Because the rule is a set of parent–child comparisons, checking it takes a single pass. The most direct version walks every non-root index and compares it with its parent:
def is_max_heap(a):
n = len(a)
for i in range(1, n):
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])) # FalseThe loop does exactly n - 1 comparisons, one per edge in the tree, so it runs in O(n) time and O(1) extra space. It returns at the first violation, so an invalid array may be rejected much sooner.
The test is <, not <=. Equal values are allowed. A parent may equal its child, so [5, 5, 5] is a valid max-heap. If you write <= you reject heaps that contain duplicates, which is a subtle bug because the checker still passes most tests that use distinct values.
Reporting Every Violation
When debugging a heap implementation, a yes/no answer is less useful than a list of the broken pairs. This version returns every (parent, child) index pair that violates the rule:
def heap_violations(a):
bad = []
for i in range(1, len(a)):
p = (i - 1) // 2
if a[p] < a[i]:
bad.append((p, i))
return bad
print(heap_violations([9, 7, 8, 3, 5, 6])) # []
print(heap_violations([3, 7, 8])) # [(0, 1), (0, 2)]
print(heap_violations([9, 3, 8, 7])) # [(1, 3)]The last example shows that a violation can be deep in the tree even when the root is correct. In [9, 3, 8, 7], the root 9 beats both children, but index 1 holds 3 and its child at index 3 holds 7.
Checking a Single Subtree
The next chapter's sift-down operation works on one subtree at a time, inside a prefix a[0:end] of the array. It assumes that both child subtrees of a node are already heaps, even when the node itself breaks the rule. A subtree checker that respects an end bound lets you test that assumption directly:
def is_max_heap_subtree(a, root, end=None):
if end is None:
end = len(a)
stack = [root]
while stack:
i = stack.pop()
for c in (2 * i + 1, 2 * i + 2):
if c < end:
if a[c] > a[i]:
return False
stack.append(c)
return True
a = [1, 7, 8, 3, 5, 6]
print(is_max_heap_subtree(a, 0)) # False: root 1 is smaller than its children
print(is_max_heap_subtree(a, 1)) # True: 7 >= 3 and 7 >= 5
print(is_max_heap_subtree(a, 2)) # True: 8 >= 6This array is a heap everywhere except at the root. Sift-down is designed to repair that exact situation. The end parameter matters later too. During heap sort, the tail of the array holds already-sorted elements that are no longer part of the heap, and the checker must ignore them.
Worked Examples
| Array | Max-heap? | Reason |
|---|---|---|
| `[9, 7, 8, 3, 5, 6]` | Yes | All five parent–child pairs satisfy parent ≥ child |
| `[9, 8, 7, 6, 5, 3]` | Yes | A descending array always satisfies the rule |
| `[3, 5, 6, 7, 8, 9]` | No | Root 3 is smaller than child 5 (an ascending array of length ≥ 2 never qualifies) |
| `[5, 5, 5]` | Yes | Equality is allowed |
| `[9, 3, 8, 7]` | No | Index 1 (value 3) is smaller than its child at index 3 (value 7) |
| `[]` and `[42]` | Yes | No parent–child pairs exist, so there is nothing to violate |
The empty and single-element cases matter in practice. Heap sort shrinks the heap down to size 1, and your code must treat that as a valid heap without special-casing it. The range(1, n) loop handles both cases naturally because it does not run at all.
Common Errors
- Using one-indexed formulas on a zero-indexed array. Textbooks that start at index 1 use parent
i // 2and children2iand2i + 1. Mixing these with Python lists compares the wrong pairs. For example,i // 2gives index 1 as its own parent. - Checking only the root. Confirming that
a[0]is the maximum does not prove the array is a heap, as[9, 3, 8, 7]shows. - Strict comparison. Rejecting equal parent and child values breaks heaps that contain duplicates.
- Ignoring the heap boundary. During sorting, only
a[0:end]is the heap. A check that reads pastendwill report false violations against the sorted tail. - Expecting sibling or left-to-right order. Code that assumes
a[1] >= a[2]will fail on valid heaps.
Exercises
Exercise
Is [10, 9, 4, 8, 9, 3, 1] a max-heap? If not, list every violating (parent, child) index pair.
Show answer
Yes. The pairs are (0,1): 10 ≥ 9, (0,2): 10 ≥ 4, (1,3): 9 ≥ 8, (1,4): 9 ≥ 9, (2,5): 4 ≥ 3, (2,6): 4 ≥ 1. All hold, including the equal pair at (1,4). The value 8 at index 3 is larger than 4 at index 2, but they are on different branches, so the rule does not compare them.
Exercise
In a max-heap of 15 distinct values, which indices could hold the second largest value, and which could hold the smallest?
Show answer
The second largest must be a child of the root, so index 1 or 2. The smallest must be a leaf. With n = 15, the leaves are indices 15 // 2 = 7 through 14.
Exercise
A teammate's checker loops for i in range(1, len(a) // 2) and compares a[i] against a[(i - 1) // 2]. Give a short array it wrongly accepts.
Show answer
The loop stops before the second half of the array, so it never checks the leaves against their parents. For [9, 3, 8, 7], len(a) // 2 is 2, so it only checks i = 1 (9 ≥ 3) and returns True, missing the violation between index 1 (3) and index 3 (7). The correct loop is range(1, len(a)).
Exercise
Write a function isminheap(a) and state its time complexity.
Show answer
def isminheap(a): return all(a[(i - 1) // 2] <= a[i] for i in range(1, len(a))). It makes at most n - 1 comparisons, so it runs in O(n) time with O(1) extra space.