AlgoViz

Heapify

medium 16 min

Heapify is how a binary heap repairs itself.

Video lesson · Chapter 1 of 5

A bubble has one path up

0:00 / 3:51

Bottom-up heapify — The diving-bell winch

1:26Reel

Read caption

Vik builds a min-heap from seven randomly loaded diving bells, sifting down through already repaired subtrees. Fix the low hooks first. Most bells barely move.

How it works

Step through the idea, or press Play.

Step 1 of 3

Spot the violation. One value is in the wrong place: too small for its children, or too big for its parent

Understand it

Start here

What heapify means

A binary heap keeps one rule: in a max-heap every parent is at least as big as its children (in a min-heap, at most). Inserts and removals break that rule at exactly one spot. Heapify is the family of small routines that move the misplaced value up or down until the rule holds again, and the bottom-up loop that applies them to turn a whole array into a heap. Think of a championship bracket where each winner must beat the players below; someone in the wrong round climbs or drops until they fit.

  • Sift down

    A value is smaller than a child. Swap it with the larger child, repeat. Used after pop and in build-heap. O(log⁡n)O(\log n).

  • Sift up

    A value is bigger than its parent. Swap it with the parent, repeat. Used after push. O(log⁡n)O(\log n).

  • Build heap

    Sift down every parent from ⌊n/2⌋−1\lfloor n/2 \rfloor - 1 back to 0. Surprisingly O(n)O(n).

Every heapify, one loop
  1. 1ViolationHeap property broken at one node
  2. 2CompareNode against parent or children
  3. 3SwapExchange with the winner
  4. 4RepeatOne level further
  5. 5RestoredValue fits, stop

The loop runs at most once per level, so a single sift costs $O(\log n)$.

Foundations

The heap lives in an array

A heap is a complete binary tree, so it packs into a list level by level with no gaps and no pointers. Moving between parent and child is arithmetic on the index. Heap properties covers the shape and order rules in full.

Index arithmetic (0-based)

left(i)=2i+1,right(i)=2i+2,parent(i)=⌊i−12⌋,last parent=⌊n2⌋−1\text{left}(i) = 2i + 1, \qquad \text{right}(i) = 2i + 2, \qquad \text{parent}(i) = \left\lfloor \frac{i - 1}{2} \right\rfloor, \qquad \text{last parent} = \left\lfloor \frac{n}{2} \right\rfloor - 1
Slots ⌊n/2⌋\lfloor n/2 \rfloor to n−1n - 1 are leaves: about half the heap. The height is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, which bounds every sift.

The max-heap [50, 40, 30, 10, 20]

IndexValueParentChildren
050 (root)none1 and 2: 40, 30
140⌊0/2⌋=0\lfloor 0/2 \rfloor = 0: 503 and 4: 10, 20
230⌊1/2⌋=0\lfloor 1/2 \rfloor = 0: 505, 6: out of range, a leaf
310⌊2/2⌋=1\lfloor 2/2 \rfloor = 1: 40leaf
420⌊3/2⌋=1\lfloor 3/2 \rfloor = 1: 40leaf
n=5n = 5, so the last parent is ⌊5/2⌋−1=1\lfloor 5/2 \rfloor - 1 = 1. Siblings are not ordered: 30 sits right of 40 and above nothing.

Operation 1

Sift down: sink a value

sift_down(heap, i, n) in a max-heap

Two comparisons per level: find the biggest of the node and its two children. If the node wins, stop; otherwise swap with the winning child and follow the value down.
Python
def sift_down(heap, i, n):    while True:        largest = i        left, right = 2 * i + 1, 2 * i + 2        if left < n and heap[left] > heap[largest]:            largest = left        if right < n and heap[right] > heap[largest]:            largest = right        if largest == i:            return        heap[i], heap[largest] = heap[largest], heap[i]        i = largesth = [10, 50, 30, 40, 20]sift_down(h, 0, len(h))print(h)   # [50, 40, 30, 10, 20]: 10 swapped with 50, then with 40
Iterative sift down: O(log⁡n)O(\log n) time, O(1)O(1) extra space. The example is a root that is too small, as after a pop.
Edit and run it in your browser

The contract

Sift down assumes healthy subtrees

Sift down (often called heapify(arr, n, i)) only repairs node ii. It is correct only if both subtrees of $i$ are already heaps: then the maximum of the subtree must be ii or one of its two children, so one comparison round finds it. In [3, 9, 6, 4, 8, 1, 5] both subtrees are heaps; sifting 3 down gives [9, 8, 6, 4, 3, 1, 5], a valid heap.

Precondition holds

  • [3, 9, 6, 4, 8, 1, 5]: left 9 over 4, 8 and right 6 over 1, 5 are heaps.
  • 3 sinks below 9, then below 8, and stops on a leaf.
  • Result [9, 8, 6, 4, 3, 1, 5] is a heap.

Precondition broken

  • [3, 9, 5, 4, 8, 1, 6]: the right subtree has 5 above 6.
  • The same call follows 3 down the left side only.
  • Result [9, 8, 5, 4, 3, 1, 6] still has 5 < 6.

Cost of one sift down

T(h)=T(h−1)+O(1)  ⇒  T(h)=O(h)≤O(⌊log⁡2n⌋)=O(log⁡n)T(h) = T(h - 1) + O(1) \;\Rightarrow\; T(h) = O(h) \le O(\lfloor \log_2 n \rfloor) = O(\log n)
Each call does constant work and moves one level down. The recursive version also uses O(h)O(h) stack; the loop uses O(1)O(1).

Operation 2

Sift up: bubble a value

Insert puts the new value in the next free slot, the end of the array, which keeps the tree complete. If it is bigger than its parent, swap and repeat. Only one comparison per level, against the parent. Inserting 20 into [15, 13, 10, 9, 8, 5, 7]: append at index 7 under 9, then swap past 9, 13 and 15 to reach the root: [20, 15, 10, 13, 8, 5, 7, 9]. More in heap operations.

sift_up(heap, i) in a max-heap

Two ways out: the value reaches the root, or it meets a parent at least as big.
Python
def sift_up(heap, i):    while i > 0:        parent = (i - 1) // 2        if heap[i] > heap[parent]:            heap[i], heap[parent] = heap[parent], heap[i]            i = parent        else:            breakdef push(heap, value):    heap.append(value)    sift_up(heap, len(heap) - 1)h = [50, 30, 40, 10, 20]push(h, 60)print(h)   # [60, 30, 50, 10, 20, 40]h = [15, 13, 10, 9, 8, 5, 7]push(h, 20)print(h)   # [20, 15, 10, 13, 8, 5, 7, 9]
Push with sift up: O(log⁡n)O(\log n).
Edit and run it in your browser

Push 60 into [50, 30, 40, 10, 20]

iParentCompareArray after
52 (40)60>4060 > 40: swap[50, 30, 60, 10, 20, 40]
20 (50)60>5060 > 50: swap[60, 30, 50, 10, 20, 40]
0noneat the root: stop[60, 30, 50, 10, 20, 40]
2 comparisons and 2 swaps; never more than the height ⌊log⁡26⌋=2\lfloor \log_2 6 \rfloor = 2.

Side by side

Sift up vs sift down

Sift upSift down
DirectionToward the rootToward the leaves
Compares withParent onlyBoth children
Comparisons per level12
Used afterInsert (push)Extract (pop), and in build-heap
Cost bounded byDepth of the nodeHeight of the node
TimeO(log⁡n)O(\log n)O(log⁡n)O(\log n)
The last row is the whole secret of the O(n)O(n) build: most nodes are deep but short.

Which direction?

In a min-heap, swap the key rules: a smaller key sifts up, a bigger key sifts down.

Operation 3

Build a heap bottom up

Leaves are already one-node heaps. Start at the last parent ⌊n/2⌋−1\lfloor n/2 \rfloor - 1 and sift each node down, moving left to the root. When a node is processed both of its subtrees are heaps, which is exactly the contract above. Heap sort uses this as its first phase and walks [4, 10, 3, 5, 1] to [10, 5, 3, 4, 1] step by step.

build_max_heap(a)

Going backwards matters: going forwards from the root, a node would be sifted before its subtrees are heaps.

Worked example: [3, 15, 13, 9, 8, 5, 10, 4, 1, 6, 17]

  1. 1

    Setup

    n=11n = 11, last parent ⌊11/2⌋−1=4\lfloor 11/2 \rfloor - 1 = 4. Slots 5 to 10 are leaves.

  2. 2

    i = 4 (8)

    Children 6 and 17: swap with 17. 8 lands on a leaf.

  3. 3

    i = 3 (9), i = 2 (13)

    9 beats 4 and 1; 13 beats 5 and 10. No swaps.

  4. 4

    i = 1 (15)

    Children 9 and 17: swap with 17. 15 then beats 6 and 8, stop.

  5. 5

    i = 0 (3)

    3 sinks below 17, then 15, then 8: three levels, the full height.

  6. 6

    Done

    [17, 15, 13, 9, 8, 5, 10, 4, 1, 6, 3] after 16 comparisons and 5 swaps.

More inputs

InputAfter buildComparisonsSwaps
[4, 10, 3, 5, 1][10, 5, 3, 4, 1]62
[1, 2, 3, 4, 5][5, 4, 3, 1, 2]63
[1, 2, 3, 4, 5, 6, 7][7, 5, 6, 4, 2, 1, 3]84
[9, 7, 6, 5, 4, 3, 2]unchanged: already a heap60
[15, 10, 13, 8, 9, 5, 7]unchanged: already a heap60
A descending array always satisfies parent ≥\ge child, so building it costs comparisons only.

Deep dive

Why build-heap is O(n)

Calling an O(log⁡n)O(\log n) routine about n/2n/2 times looks like O(nlog⁡n)O(n \log n). But a sift down costs the height of its node, not log⁡n\log n, and short nodes dominate: half the nodes are leaves (height 0), a quarter have height 1, an eighth height 2, and only the root has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor.

Worst-case swaps for a 15-node heap

Height hNodesSwaps each, at mostWork
0 (leaves)800
1414
2224
3 (root)133
Total1511, less than nn
For a perfect tree the sum of heights is exactly n−log⁡2(n+1)n - \log_2(n + 1): 15−4=1115 - 4 = 11.

The sum Σ h / 2^h

T(n)≤∑h=0⌊log⁡2n⌋⌈n2h+1⌉c h  ≤  c n2∑h=0∞h2h+O(log⁡2n)  =  c n+O(log⁡2n)  =  O(n)T(n) \le \sum_{h=0}^{\lfloor \log_2 n \rfloor} \left\lceil \frac{n}{2^{h+1}} \right\rceil c\,h \;\le\; \frac{c\,n}{2} \sum_{h=0}^{\infty} \frac{h}{2^{h}} + O(\log^2 n) \;=\; c\,n + O(\log^2 n) \;=\; O(n)
At most ⌈n/2h+1⌉\lceil n / 2^{h+1} \rceil nodes have height hh, and each costs O(h)O(h). The ceilings add at most one node per level.

Why the series is 2

∑h=0∞xh=11−x  →  ddx, ×x    ∑h=0∞h xh=x(1−x)2  →  x=1/2    1/21/4=2\sum_{h=0}^{\infty} x^{h} = \frac{1}{1 - x} \;\xrightarrow{\;\frac{d}{dx},\ \times x\;}\; \sum_{h=0}^{\infty} h\,x^{h} = \frac{x}{(1 - x)^2} \;\xrightarrow{\;x = 1/2\;}\; \frac{1/2}{1/4} = 2
Differentiate the geometric series and multiply by xx. The terms 12,24,38,416,…\frac{1}{2}, \frac{2}{4}, \frac{3}{8}, \frac{4}{16}, \dots shrink fast enough to converge.

Head to head

Bottom-up build vs n inserts

You could also build a heap by pushing the values one at a time. Each push sifts up and pays the depth of its slot, and most slots are deep: half of all nodes sit on the bottom level at depth about log⁡2n\log_2 n.

Cost of n inserts

∑k=1n⌊log⁡2k⌋  =  Θ(log⁡2n!)  =  Θ(nlog⁡n)\sum_{k=1}^{n} \lfloor \log_2 k \rfloor \;=\; \Theta(\log_2 n!) \;=\; \Theta(n \log n)
Insert number kk can climb ⌊log⁡2k⌋\lfloor \log_2 k \rfloor levels. By Stirling, log⁡2n!≈nlog⁡2n−1.44n\log_2 n! \approx n \log_2 n - 1.44n. Ascending input hits the worst case: every new value climbs to the root.
nBottom up (sift down), worst swapsn inserts (sift up), worst swapsnlog⁡2nn \log_2 n
7410about 20
151134about 59
1,0231,0138,194about 10,229
1,000,000999,993about 18 millionabout 19.9 million
On [1, 2, ..., 7] the two methods make 4 and 10 swaps and produce different heaps: [7, 5, 6, 4, 2, 1, 3] and [7, 4, 6, 1, 3, 2, 5]. Both are valid.

In Python

heapq.heapify

Python's heapq module runs these routines on a plain list. heapq.heapify(xs) is the bottom-up build: in place, O(n)O(n), returns None. It always makes a min-heap, so xs[0] is the smallest value.

Python
import heapqtasks = [5, 3, 8, 1, 9, 2]heapq.heapify(tasks)            # O(n), in placeprint(tasks)                    # [1, 3, 2, 5, 9, 8]heapq.heappush(tasks, 0)        # sift up: O(log n)print(heapq.heappop(tasks))     # 0, then sift down: O(log n)scores = [40, 90, 70, 20]max_heap = [-s for s in scores] # negate for a max-heapheapq.heapify(max_heap)print(-max_heap[0])             # 90
Build once, then push and pop. Negate values for a max-heap.
Edit and run it in your browser
CallWhat it doesTime
heapify(xs)Bottom-up build, min-heapO(n)O(n)
heappush(xs, v)Append, then sift upO(log⁡n)O(\log n)
heappop(xs)Move last to root, sift down, return old rootO(log⁡n)O(\log n)
heapreplace(xs, v)Pop then push, one sift downO(log⁡n)O(\log n)
heappushpop(xs, v)Push then pop, often no sift at allO(log⁡n)O(\log n)
nlargest(k, xs)Top k with a size-k heapO(nlog⁡k)O(n \log k)

Cheat sheet

Costs and a mnemonic

OperationTimeExtra spaceUse case
Sift down (once)O(log⁡n)O(\log n)O(1)O(1) loop, O(log⁡n)O(\log n) recursivePop, heap sort, build-heap
Sift up (once)O(log⁡n)O(\log n)O(1)O(1)Push, priority queue insert
Build heap, bottom upO(n)O(n)O(1)O(1)Initial construction
Build heap, n insertsO(nlog⁡n)O(n \log n)O(1)O(1)Values arrive one by one
Peek the rootO(1)O(1)O(1)O(1)Max or min lookup
BUBBLE
  1. 1BottomStart at the last parent or the new leaf
  2. 2Up or downPick the direction
  3. 3Big or littleCompare with parent or children
  4. 4BumpSwap if the rule is broken
  5. 5LoopRepeat one level on
  6. 6EndStop when no swap is needed

Recap

Key takeaways

Key points

  • Sift down sinks a too-small value below its larger child; sift up lifts a too-big value above its parent. Each is O(log⁡n)O(\log n).
  • Sift down assumes both subtrees are already heaps; that is why build-heap runs backwards.
  • Build-heap: sift down every parent from ⌊n/2⌋−1\lfloor n/2 \rfloor - 1 to 0.
  • Build-heap is O(n)O(n) because work is ∑hn2h+1h≤n\sum_h \frac{n}{2^{h+1}} h \le n; building with nn inserts is Θ(nlog⁡n)\Theta(n \log n).
  • Sift down pays height, sift up pays depth: most nodes are short but deep.
  • heapq.heapify is the O(n)O(n) min-heap build; negate values for a max-heap.

Sources