08-heaps
Min-Heap Pop (Sift Down)
Remove the minimum value, move the last item to the root, and sift downward.
Algorithm
Steps
- Store the heap in an array.
- Compare parent and child indexes instead of building explicit tree nodes.
- Swap only when the heap order is violated.
- Print the deterministic final heap state for replay comparison.
Complexity
- Time: O(log n)
- Space: O(1) extra
sift down
After removing the root, the last value moves to the root and swaps with the smaller child until order is restored.
Visual walkthrough
Ruby DSA Implementation
basic.rb
def list_string(values) = "[#{values.join(', ')}]"
def heap_insert(heap, value)
heap << value
child = heap.length - 1
while child > 0
parent = (child - 1) / 2
break if heap[parent] <= heap[child]
heap[parent], heap[child] = heap[child], heap[parent]
child = parent
end
end
def heap_pop(heap)
smallest = heap[0]
heap[0] = heap.pop
parent = 0
loop do
left = parent * 2 + 1
right = left + 1
break if left >= heap.length
child = right < heap.length && heap[right] < heap[left] ? right : left
break if heap[parent] <= heap[child]
heap[parent], heap[child] = heap[child], heap[parent]
parent = child
end
smallest
end
heap = [1, 4, 2, 9, 6, 7]
popped = heap_pop(heap)
puts "#{popped} -> #{list_string(heap)}"
Implementation notes
- The heap is a Ruby
Arrayarranged as a binary min-heap in level order. heap_pop(heap)mutates the passed array and returns the removed root value.smallest = heap[0]saves the popped value before the heap is rearranged.heap[0] = heap.popremoves the last array slot and moves that returned value into the root position.- Sift-down starts with
parent = 0; each loop computesleft = parent * 2 + 1andright = left + 1. break if left >= heap.lengthstops when the parent has no children.- The smaller child is selected by
right < heap.length && heap[right] < heap[left] ? right : left. - The min-heap order check is
break if heap[parent] <= heap[child]. - Swaps use Ruby parallel assignment:
heap[parent], heap[child] = heap[child], heap[parent]. - The trace starts from
[1, 4, 2, 9, 6, 7], returns1, moves7to the root, then swaps7with smaller child2. - The final
putsformats both values as1 -> [2, 4, 7, 9, 6].
Output
1 -> [2, 4, 7, 9, 6]