Python 3D Academyবাংলা

A heap built from scratch: sift up and sift down

🌍 In real life. In a hospital's emergency room, patients are not seen in the order they arrive. A nurse gives each one an urgency number, 1 for the most urgent, and the doctor always sees the most urgent patient waiting. New patients keep arriving all the time, and each one may jump ahead of people already waiting.

That is a priority queue: add anything at any moment, and always take out the item with the best priority next. A sorted list could do it, but every new patient would have to be squeezed into place. A heap does it with only a few swaps per patient, and Python's heapq (Chapter 30) is one. This lesson builds it from scratch.

The idea in one sentence: a binary heap is a list read as a tree, where index i's children are 2i + 1 and 2i + 2, kept so that every parent is no bigger than its children; then the smallest is always at index 0, a new item sifts up from the end, and after the top is taken the last item sifts down from the top.

Its words:

  • priority queue: a collection where you add items and always remove the one with the best (here, smallest) priority
  • heap rule: heap[i] <= heap[2*i + 1] and heap[i] <= heap[2*i + 2] wherever those children exist
  • complete tree: every level full except maybe the last, which fills from the left; a list is always exactly that shape
  • parent of i: (i - 1) // 2
  • sift up: swap an item with its parent while it is smaller
  • sift down: swap an item with its smaller child while it is bigger

How it works, step by step:

  1. push x: append x at the end (the bottom of the tree), then sift it up until its parent is no bigger
  2. pop: the answer is heap[0]; move the last item into its place, then sift that item down, always swapping with the smaller child, until both children are no smaller
  3. peek: heap[0], without changing anything

Watch the emergency room: urgency 1 arrives and climbs to the top, then the two most urgent patients are seen:

Why it is correct. The heap rule holds everywhere except at the one item that is moving. Sifting up: when x swaps with a bigger parent p, x is smaller than p, and p was no bigger than its other child, so x is smaller than both of its new children. The only place left that can break the rule is between x and its new parent, and the next comparison checks exactly that. Sifting down: swapping with the smaller child c puts c on top of the other child, which is no smaller than c, so that pair is fine; again only the moving item can still be out of place. Each step moves the problem one level, and it ends at the top or at the bottom.

What it costs, by counting. A heap of n items is a complete tree, so it has ⌊log₂ n⌋ + 1 levels, and an item moves at most one level per swap:

  • 15 items: at most 3 swaps for a push or a pop
  • 1,000 items: at most 9
  • 1,000,000 items: at most 19

So push and pop are O(log n) and peek is O(1). Compare the other ways: an unsorted list adds in O(1) but must search all n to remove the smallest, and a sorted list removes in O(1) but must shift up to n items to add one.

def heap_push(heap, x):
    heap.append(x)                       # join at the bottom of the tree
    i = len(heap) - 1
    while i > 0 and heap[i] < heap[(i - 1) // 2]:
        parent = (i - 1) // 2
        heap[i], heap[parent] = heap[parent], heap[i]   # climb past a bigger parent
        i = parent

def heap_pop(heap):
    top = heap[0]                        # the smallest; IndexError if the heap is empty
    last = heap.pop()                    # take the last item off the end
    if heap:
        heap[0] = last                   # it fills the hole at the top...
        i = 0
        while True:                      # ...and sinks below any smaller child
            child = 2 * i + 1
            if child >= len(heap):
                break
            if child + 1 < len(heap) and heap[child + 1] < heap[child]:
                child += 1               # the smaller of the two children
            if heap[i] <= heap[child]:
                break
            heap[i], heap[child] = heap[child], heap[i]
            i = child
    return top

heap = []
for urgency in [5, 2, 8, 1, 9, 3]:
    heap_push(heap, urgency)
print(heap)                              # a heap, not a sorted list
print(heap_pop(heap), heap_pop(heap), heap_pop(heap))
print(heap)

# Python's own heap does the same work, on a plain list
import heapq
waiting = []
for patient in [(3, "rafi"), (1, "mina"), (2, "joy")]:
    heapq.heappush(waiting, patient)     # tuples compare by urgency first
print(heapq.heappop(waiting))
print(waiting[0])                        # peek at the next one

Mistakes and edge cases.

  • sifting down with the bigger child: the bigger child would end up above the smaller one and break the rule; always swap with the smaller child
  • forgetting that only one child may exist: check child + 1 < len(heap) before reading the right child
  • popping an empty heap: heap[0] on [] raises IndexError; heapq.heappop([]) does the same
  • heap[-1] is not the biggest: a heap only promises the smallest at the top; the rest is not sorted
  • a max-heap with heapq: push -x and negate what comes out
  • ties between tuples: (2, "zia") and (2, "amy") fall back to comparing the names, so amy goes first even if zia came first; add the arrival number as the second item to keep first come, first served

Quiz

  1. What does this print?

    import heapq
    h = []
    for x in [6, 4, 9, 1]:
        heapq.heappush(h, x)
    print(h)
  2. In a heap stored as a list, what are the indexes of the children of index 2, and of the parent of index 7?

    • Children 5 and 6; parent 3
    • Children 4 and 5; parent 3
    • Children 5 and 6; parent 4
  3. Two patients have urgency 2. What does this print?

    import heapq
    waiting = []
    for patient in [(2, "zia"), (1, "bob"), (2, "amy")]:
        heapq.heappush(waiting, patient)
    print([heapq.heappop(waiting)[1] for _ in range(3)])
  4. After a pop, this sometimes leaves a parent bigger than a child. Which line is wrong?

    def sift_down(heap, i):
        while True:
            child = 2 * i + 1
            if child >= len(heap):
                break
            if child + 1 < len(heap) and heap[child + 1] > heap[child]:
                child += 1
            if heap[i] <= heap[child]:
                break
            heap[i], heap[child] = heap[child], heap[i]
            i = child
  5. A heap holds 1,000,000 items. At most how many swaps does one push take?

    • 19: one per level below the top
    • About 1,000
    • About 500,000

Coding tasks

  1. Build it yourself, without heapq: write heap_push(heap, x), which adds x to the list heap (already a min-heap) and sifts it up so the heap rule holds again. It changes the list in place and returns nothing.

  2. Still without heapq: write heap_pop(heap), which removes and returns the smallest item of a non-empty min-heap, moving the last item to the top and sifting it down (swap with the smaller child) so the heap rule holds again.

  3. Now use heapq. Write treat_order(patients): patients is a list of (urgency, name) in the order they arrived; return the names in the order the doctor sees them, most urgent (smallest number) first, and on equal urgency the one who arrived first.