Remove the minimum value, move the last item to the root, and sift downward.

Algorithm

Steps

  1. Store the heap in an array.
  2. Compare parent and child indexes instead of building explicit tree nodes.
  3. Swap only when the heap order is violated.
  4. 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)}"

After popping the minimum, the last value moves to the root and sifts down by swapping with the smaller child.

Step 1 - Replace root

The saved minimum is 1; the last value 7 moves to the root before sifting down.

Replacement state [7, 4, 2, 9, 6] with removed value 1.1removed7root4left2smaller9i36i4

Step 2 - Swap with the smaller child

7 swaps with 2, producing the final heap [2, 4, 7, 9, 6].

Final heap after pop and one sift-down swap.2root4i17i29i36i4

Implementation notes

  • The heap is a Ruby Array arranged 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.pop removes the last array slot and moves that returned value into the root position.
  • Sift-down starts with parent = 0; each loop computes left = parent * 2 + 1 and right = left + 1.
  • break if left >= heap.length stops 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], returns 1, moves 7 to the root, then swaps 7 with smaller child 2.
  • The final puts formats both values as 1 -> [2, 4, 7, 9, 6].

Output

1 -> [2, 4, 7, 9, 6]