ENع
←Binary heaps
Lesson 12 · Hashing and heaps

Binary heaps: sift up and sift down

12 min8 steps5 questionsIntermediate
About this lesson

A heap keeps the smallest item on top without sorting everything. Here it is a plain Python list read as a tree: index 0 is the root and the children of i sit at 2i + 1 and 2i + 2. Watch heappush(h, 1) append and sift up three levels, then heappop(h) move the last item to the root and sift it down, one swap per level. The Software lessons "Trees" and "How fast is fast? Big O" cover binary trees and O(log n).

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 12 · Interactive
01 / 08

A list read as a tree

A binary heap is a plain Python list read as a tree. h[0] is the root. The item at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) // 2. No pointers are stored.

h = [2, 4, 3, 8, 5, 7, 6]

parent = (i - 1) // 2
left   = 2 * i + 1
right  = 2 * i + 2

i = 0: children 1, 2      (values 4, 3)
i = 1: children 3, 4      (values 8, 5)
i = 2: children 5, 6      (values 7, 6)
i = 6: parent (6 - 1) // 2 = 2
Loading figure…
or ← →
Read the lesson step by step
  1. A list read as a tree

    A binary heap is a plain Python list read as a tree. h[0] is the root. The item at index i has its children at 2i + 1 and 2i + 2, and its parent at (i − 1) // 2. No pointers are stored.

    h = [2, 4, 3, 8, 5, 7, 6]
    
    parent = (i - 1) // 2
    left   = 2 * i + 1
    right  = 2 * i + 2
    
    i = 0: children 1, 2      (values 4, 3)
    i = 1: children 3, 4      (values 8, 5)
    i = 2: children 5, 6      (values 7, 6)
    i = 6: parent (6 - 1) // 2 = 2
  2. The heap rule

    The rule: every parent is less than or equal to its children. So the smallest item is always h[0]. The rest is only loosely ordered: [2, 4, 3, 8, 5, 7, 6] is a valid heap, but it is not sorted.

    min-heap rule: h[i] <= h[2*i + 1] and h[i] <= h[2*i + 2]
    
      h[0] = 2  <=  h[1] = 4
      h[0] = 2  <=  h[2] = 3
      h[1] = 4  <=  h[3] = 8
      h[1] = 4  <=  h[4] = 5
      h[2] = 3  <=  h[5] = 7
      h[2] = 3  <=  h[6] = 6
    
    so h[0] = 2 is the smallest, yet 8 comes before 5, 7 and 6: not sorted
  3. Push: append at the end

    heapq.heappush(h, 1) first appends 1 at the end, index 7. The tree stays complete: filled level by level, left to right. Its parent is at (7 − 1) // 2 = 3 and holds 8. 8 > 1 breaks the rule.

    def push(h, x):
        h.append(x)
        sift_up(h, len(h) - 1)
    
    h.append(1)  -> index 7
    h = [2, 4, 3, 8, 5, 7, 6, 1]
    parent of 7 = (7 - 1) // 2 = 3, h[3] = 8 > 1
  4. Sift up

    Sift up: while the new item is smaller than its parent, swap the two. 1 swaps with 8, then with 4, then with 2. Now it is the root, so it stops: 3 swaps, one per level.

    def sift_up(h, i):
        while i > 0:
            p = (i - 1) // 2
            if h[p] <= h[i]:
                break
            h[p], h[i] = h[i], h[p]
            i = p
    
    swap h[3] and h[7]
    swap h[1] and h[3]
    swap h[0] and h[1]
    h = [1, 2, 3, 4, 5, 7, 6, 8]
  5. Pop: take the root

    heapq.heappop(h) returns h[0], the smallest item: 1. To keep the tree complete, the last item, 8 from index 7, moves into the root. The list is back to 7 items, but 8 on top breaks the rule.

    def pop(h):
        top = h[0]
        last = h.pop()
        if h:
            h[0] = last
            sift_down(h, 0)
        return top
    
    top = h[0] = 1
    last item 8 moves from index 7 to index 0
    h = [8, 2, 3, 4, 5, 7, 6]
    children of 0: h[1] = 2, h[2] = 3, both < 8
  6. Sift down

    Sift down: swap the item with its smaller child while that child is smaller. The smaller one, so the new parent is no bigger than the other child. 8 swaps with 2, then with 4. Index 3 has no children left, so it stops.

    def sift_down(h, i):
        n = len(h)
        while 2 * i + 1 < n:
            c = 2 * i + 1
            if c + 1 < n and h[c + 1] < h[c]:
                c += 1
            if h[i] <= h[c]:
                break
            h[i], h[c] = h[c], h[i]
            i = c
    
    i = 0: children 2, 3 -> smaller is 2 (index 1) < 8: swap
    i = 1: children 4, 5 -> smaller is 4 (index 3) < 8: swap
    i = 3: left child 7 is not < len(h) = 7: stop
    h = [2, 4, 3, 8, 5, 7, 6]
  7. One swap per level

    Each swap moves one level. A complete tree of n items has ⌊log₂ n⌋ + 1 levels, so a sift makes at most ⌊log₂ n⌋ swaps: 3 for 8 items, 19 for a million. Push and pop are O(log n); reading h[0] is O(1).

    levels of a complete tree with n items: floor(log2 n) + 1
      n = 7        levels 3   max swaps 2
      n = 8        levels 4   max swaps 3
      n = 15       levels 4   max swaps 3
      n = 16       levels 5   max swaps 4
      n = 1000     levels 10  max swaps 9
      n = 1000000  levels 20  max swaps 19
    
    push: O(1) amortised append + O(log n) sift up
    pop:  O(1) list pop       + O(log n) sift down
    peek: h[0], O(1)
  8. Python's heapq

    Python's heapq module does exactly this to a plain list. heappush(h, 1) then heappop(h) returns 1 and leaves h = [2, 4, 3, 8, 5, 7, 6] again. It is a min-heap; Python 3.14 adds heappush_max and heappop_max for a max-heap.

    import heapq
    h = [2, 4, 3, 8, 5, 7, 6]
    heapq.heappush(h, 1)
    h            # [1, 2, 3, 4, 5, 7, 6, 8]
    heapq.heappop(h)  # 1
    h            # [2, 4, 3, 8, 5, 7, 6]
    h[0]         # 2, the smallest, without popping

Quiz Unlocks after the last step.