Keep only the largest k values by maintaining a small min-heap.

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. @end @complexity
  • Time: O(n log k)
  • Space: O(k) @end
bounded heap For top-k largest values, a min-heap of size k keeps the current cutoff at the root.

Fortran DSA Implementation

basic.f90
program main
  implicit none
  integer :: heap(16), n, popped, top(16)
  heap = 0; n = 0
  call keep_top(heap, n, 5, 3); call keep_top(heap, n, 1, 3); call keep_top(heap, n, 9, 3)
  call keep_top(heap, n, 3, 3); call keep_top(heap, n, 7, 3); call keep_top(heap, n, 2, 3)
  top = 0; top(1:3) = [9, 7, 5]
  call print_list(top, 3)
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

@end @output [9, 7, 5] @end