Data Structures19 sections · 729 units
Open in Course

Bubble Down Details

Choosing the right child

When bubbling down, always swap with the smaller child (in a min-heap):

function bubbleDown(heap, i)
    n := length of heap
    while true
        smallest := i
        left := 2 * i + 1
        right := 2 * i + 2

        if left < n and heap[left] < heap[smallest]
            smallest := left
        if right < n and heap[right] < heap[smallest]
            smallest := right

        if smallest = i
            break
        swap heap[i] and heap[smallest]
        i := smallest

Swapping with the smaller child ensures the heap property is maintained.