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

Fortran DSA Implementation

basic.f90
program main
  implicit none
  integer :: heap(16), n, popped, top(16)
  heap = 0; heap(1:6) = [1, 4, 2, 9, 6, 7]; n = 6
  call heap_pop(heap, n, popped)
  write(*, '(I0,A)', advance='no') popped, ' -> '
  call print_list(heap, n)
contains
  subroutine print_list(values, count)
    integer, intent(in) :: values(16), count
    integer :: i
    write(*, '(A)', advance='no') '['
    do i = 1, count
      if (i > 1) write(*, '(A)', advance='no') ', '
      write(*, '(I0)', advance='no') values(i)
    end do
    print '(A)', ']'
  end subroutine print_list
  subroutine swap(a, b)
    integer, intent(inout) :: a, b
    integer :: tmp
    tmp = a; a = b; b = tmp
  end subroutine swap
  subroutine heap_insert(heap, n, value)
    integer, intent(inout) :: heap(16), n
    integer, intent(in) :: value
    integer :: child, parent
    n = n + 1; heap(n) = value; child = n
    do while (child > 1)
      parent = child / 2
      if (heap(parent) <= heap(child)) exit
      call swap(heap(parent), heap(child))
      child = parent
    end do
  end subroutine heap_insert
  subroutine heap_pop(heap, n, popped)
    integer, intent(inout) :: heap(16), n
    integer, intent(out) :: popped
    integer :: parent, left, right, child
    popped = heap(1); heap(1) = heap(n); n = n - 1; parent = 1
    do
      left = parent * 2; right = left + 1
      if (left > n) exit
      child = left
      if (right <= n .and. heap(right) < heap(left)) child = right
      if (heap(parent) <= heap(child)) exit
      call swap(heap(parent), heap(child))
      parent = child
    end do
  end subroutine heap_pop
  subroutine keep_top(heap, n, value, k)
    integer, intent(inout) :: heap(16), n
    integer, intent(in) :: value, k
    integer :: removed
    call heap_insert(heap, n, value)
    if (n > k) call heap_pop(heap, n, removed)
  end subroutine keep_top
end program main

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

Output

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