TExcelTAD
Home › Sorting & Order Statistics › Binary Heaps and the Heap Property

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 lg⁡n\lg n levels for nn 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 0,1,…,n−10, 1, \ldots, n-1 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

parent⁡(i)=⌊i−12⌋,left⁡(i)=2i+1,right⁡(i)=2i+2\operatorname{parent}(i) = \left\lfloor \frac{i - 1}{2} \right\rfloor, \qquad \operatorname{left}(i) = 2i + 1, \qquad \operatorname{right}(i) = 2i + 2

and a child index is only valid when it is less than nn. (With 1-based indices the formulas are the prettier ⌊i/2⌋\lfloor i/2 \rfloor, 2i2i and 2i+12i + 1; the 0-based ones are the same thing shifted by one.)

python · try it yourself
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 += 1
node 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[parent⁡(i)]≥a[i]for 1≤i≤n−1a[\operatorname{parent}(i)] \ge a[i] \quad \text{for } 1 \le i \le n - 1

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:

python · try it yourself
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 (1515 comes after 99).

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.

cpp · try it yourself
#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.

python · try it yourself
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 n≥1n \ge 1 elements has height ⌊lg⁡n⌋\lfloor \lg n \rfloor.

Proof. If the height is hh, levels 00 to h−1h - 1 are full and level hh has between 1 and 2h2^h nodes, so 2h≤n≤2h+1−1<2h+12^h \le n \le 2^{h+1} - 1 < 2^{h+1}. Taking logarithms, h≤lg⁡n<h+1h \le \lg n < h + 1, which says h=⌊lg⁡n⌋h = \lfloor \lg n \rfloor.

Fact 2. The leaves are exactly the positions ⌊n/2⌋,…,n−1\lfloor n/2 \rfloor, \ldots, n - 1, so there are ⌈n/2⌉\lceil n/2 \rceil of them. More generally, a heap has at most ⌈n/2h+1⌉\lceil n / 2^{h+1} \rceil nodes of height hh.

Proof of the first part. Position ii has a left child exactly when 2i+1≤n−12i + 1 \le n - 1, that is i≤n2−1i \le \frac{n}{2} - 1, which for an integer ii means i<⌊n/2⌋i < \lfloor n/2 \rfloor. The general bound follows by induction on hh: removing all the leaves leaves a heap of ⌊n/2⌋\lfloor n/2 \rfloor nodes whose leaves are the old height-1 nodes, and so on. The program checks both facts exhaustively for every nn up to 700.

python · try it yourself
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 O(lg⁡n)O(\lg n): 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 heapq module is a min-heap on a plain list with exactly this layout, and C++'s std::priority_queue is 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?

  1. 8 and 9
  2. 9 and 10
  3. 5 and 6
  4. 2 and 3

What is the height of a heap with n=100n = 100 elements?

  1. 5
  2. 6
  3. 7
  4. 50

Which statement about a max-heap is true?

  1. It is sorted in descending order
  2. Every node is at least every node in its subtree
  3. Each left child is smaller than its right sibling
  4. The minimum is at position n−1n - 1

Which positions are leaves in a heap of n=11n = 11 elements?

  1. 5 to 10
  2. 6 to 10
  3. 4 to 10
  4. only 10