Binary Heaps and the Heap Property
A binary heap is an array that you are allowed to look at as a tree. No pointers are stored: the tree is implied by index arithmetic, so a heap costs exactly as much memory as the array itself. One local rule, the heap property, makes the largest (or smallest) element sit at the root, and the tree's shape keeps it shallow, about levels for elements. Those two facts are all that heapsort and priority queues need.
The Heaps lesson in the DSA course introduces heaps by example. This lesson states the definitions precisely and proves the facts about height and leaves that the next lessons rely on.
The shape: a nearly complete tree stored in an array
Take the array positions and arrange them in a binary tree level by level, left to right: position 0 is the root, positions 1 and 2 are its children, 3 to 6 the next level, and so on. Every level is full except possibly the last, which is filled from the left. Such a tree is called nearly complete.
With 0-based indices the family relations are
and a child index is only valid when it is less than . (With 1-based indices the formulas are the prettier , and ; the 0-based ones are the same thing shifted by one.)
def parent(i): return (i - 1) // 2
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
n = 10
for i in range(n):
kids = [c for c in (left(i), right(i)) if c < n]
p = parent(i) if i > 0 else "-"
print(f"node {i}: parent {p}, children {kids}")
# print the positions level by level: level d holds positions 2^d - 1 .. 2^(d+1) - 2
d = 0
while 2 ** d - 1 < n:
print(f"level {d}:", list(range(2 ** d - 1, min(2 ** (d + 1) - 1, n))))
d += 1node 0: parent -, children [1, 2]
node 1: parent 0, children [3, 4]
node 2: parent 0, children [5, 6]
node 3: parent 1, children [7, 8]
node 4: parent 1, children [9]
node 5: parent 2, children []
node 6: parent 2, children []
node 7: parent 3, children []
node 8: parent 3, children []
node 9: parent 4, children []
level 0: [0]
level 1: [1, 2]
level 2: [3, 4, 5, 6]
level 3: [7, 8, 9]
Positions 5 to 9 have no children: they are the leaves. Position 4 has only a left child.
The heap property
A max-heap is an array in which every node other than the root is at most its parent:
A min-heap reverses the inequality. The property only talks about parents and children, but it chains: along any path from the root down, the values never increase. So by induction on depth, every node of a max-heap is at least every node in its subtree, and in particular the maximum sits at position 0. Nothing is said about siblings or cousins; a heap is far from sorted.
Checking the property is a single loop over the non-root positions:
def is_max_heap(a):
return all(a[(i - 1) // 2] >= a[i] for i in range(1, len(a)))
def first_violation(a):
for i in range(1, len(a)):
if a[(i - 1) // 2] < a[i]:
return i
return None
examples = [
[21, 17, 12, 9, 15, 6, 3, 2, 5, 11],
[21, 17, 12, 9, 15, 6, 3, 2, 5, 11][::-1],
[9, 9, 9],
[10, 7, 9, 8, 1],
sorted([5, 3, 8, 1], reverse=True),
]
for a in examples:
v = first_violation(a)
note = "" if v is None else f" (a[{v}] = {a[v]} > parent a[{(v - 1) // 2}] = {a[(v - 1) // 2]})"
print(f"{str(a):35} max-heap: {is_max_heap(a)}{note}")[21, 17, 12, 9, 15, 6, 3, 2, 5, 11] max-heap: True
[11, 5, 2, 3, 6, 15, 9, 12, 17, 21] max-heap: False (a[4] = 6 > parent a[1] = 5)
[9, 9, 9] max-heap: True
[10, 7, 9, 8, 1] max-heap: False (a[3] = 8 > parent a[1] = 7)
[8, 5, 3, 1] max-heap: True
Two things to notice. A descending array is always a max-heap, because every parent comes before its children. The converse fails: [21, 17, 12, 9, 15, 6, 3, 2, 5, 11] is a heap but not sorted ( comes after ).
The C++ standard library has the same check, std::is_heap, for max-heaps by default; std::is_heap_until returns the first position where the property breaks.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> examples = {
{21, 17, 12, 9, 15, 6, 3, 2, 5, 11},
{10, 7, 9, 8, 1},
{9, 9, 9},
};
for (const auto& a : examples) {
auto bad = std::is_heap_until(a.begin(), a.end());
std::cout << "max-heap: " << std::boolalpha << std::is_heap(a.begin(), a.end());
if (bad != a.end()) std::cout << ", first violation at index " << (bad - a.begin());
std::cout << '\n';
}
}max-heap: true
max-heap: false, first violation at index 3
max-heap: true
Building a heap one push at a time
The animation fills a min-heap by adding values one at a time. A new value goes into the next free position, the leftmost gap in the bottom level, which keeps the shape nearly complete. Then it sifts up: while it is smaller than its parent, the two swap. The lesson Priority Queues analyses this operation; here it is a way to watch the shape and the property together.
The Python version prints the array after each push, the last state of each push in the animation.
def push(heap, x):
heap.append(x) # next free spot keeps the shape
i = len(heap) - 1
while i > 0 and heap[(i - 1) // 2] > heap[i]:
p = (i - 1) // 2
heap[p], heap[i] = heap[i], heap[p] # sift up
i = p
heap = []
for x in [7, 4, 9, 2, 6, 1]:
push(heap, x)
print(f"push {x}: {heap}")push 7: [7]
push 4: [4, 7]
push 9: [4, 7, 9]
push 2: [2, 4, 9, 7]
push 6: [2, 4, 9, 7, 6]
push 1: [1, 4, 2, 7, 6, 9]
Height and leaves
The height of a node is the number of edges on the longest downward path from it to a leaf; the height of the heap is the height of its root. Two counting facts carry all the running-time analyses in this section.
Fact 1. A heap with elements has height .
Proof. If the height is , levels to are full and level has between 1 and nodes, so . Taking logarithms, , which says .
Fact 2. The leaves are exactly the positions , so there are of them. More generally, a heap has at most nodes of height .
Proof of the first part. Position has a left child exactly when , that is , which for an integer means . The general bound follows by induction on : removing all the leaves leaves a heap of nodes whose leaves are the old height-1 nodes, and so on. The program checks both facts exhaustively for every up to 700.
import math
def heights(n):
"""height of every node of an n-element heap, computed bottom-up"""
h = [0] * n
for i in range(n - 1, -1, -1):
for c in (2 * i + 1, 2 * i + 2):
if c < n:
h[i] = max(h[i], h[c] + 1)
return h
ok = True
for n in range(1, 701):
h = heights(n)
ok &= h[0] == math.floor(math.log2(n)) # fact 1
ok &= [i for i in range(n) if h[i] == 0] == list(range(n // 2, n)) # leaves
for height in range(h[0] + 1):
ok &= h.count(height) <= math.ceil(n / 2 ** (height + 1)) # fact 2
print("facts 1 and 2 hold for n = 1..700:", ok)
n = 20
h = heights(n)
for height in range(h[0] + 1):
print(f"n = {n}, height {height}: {h.count(height):2} nodes, bound ceil(n / 2^(h+1)) = {math.ceil(n / 2 ** (height + 1))}")facts 1 and 2 hold for n = 1..700: True
n = 20, height 0: 10 nodes, bound ceil(n / 2^(h+1)) = 10
n = 20, height 1: 5 nodes, bound ceil(n / 2^(h+1)) = 5
n = 20, height 2: 3 nodes, bound ceil(n / 2^(h+1)) = 3
n = 20, height 3: 1 nodes, bound ceil(n / 2^(h+1)) = 2
n = 20, height 4: 1 nodes, bound ceil(n / 2^(h+1)) = 1
Fact 1 is why heap operations cost : they walk one root-to-leaf path. Fact 2 says most nodes are near the bottom, half of them leaves, a quarter one level up. That is the reason a heap can be built in linear time, the subject of Building a Heap in Linear Time.
Note: Python's
heapqmodule is a min-heap on a plain list with exactly this layout, and C++'sstd::priority_queueis a max-heap by default. Mixing the two conventions up is the most common heap bug.
Test yourself
In a 0-based array heap, what are the children of position 4?
- 8 and 9
- 9 and 10
- 5 and 6
- 2 and 3
What is the height of a heap with elements?
- 5
- 6
- 7
- 50
Which statement about a max-heap is true?
- It is sorted in descending order
- Every node is at least every node in its subtree
- Each left child is smaller than its right sibling
- The minimum is at position
Which positions are leaves in a heap of elements?
- 5 to 10
- 6 to 10
- 4 to 10
- only 10