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.

Bash DSA Implementation

basic.sh
#!/usr/bin/env bash
list_string() {
  local joined=""
  for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done
  printf '[%s]' "$joined"
}
heap_insert() {
  local value=$1 child parent tmp
  heap+=("$value")
  child=$((${#heap[@]} - 1))
  while (( child > 0 )); do
    parent=$(((child - 1) / 2))
    (( heap[parent] <= heap[child] )) && break
    tmp=${heap[$parent]}; heap[$parent]=${heap[$child]}; heap[$child]=$tmp
    child=$parent
  done
}
heap_pop() {
  popped=${heap[0]}
  heap[0]=${heap[-1]}
  unset 'heap[-1]'
  local parent=0 left right child tmp
  while true; do
    left=$((parent * 2 + 1)); right=$((left + 1))
    (( left >= ${#heap[@]} )) && break
    child=$left
    if (( right < ${#heap[@]} && heap[right] < heap[left] )); then child=$right; fi
    (( heap[parent] <= heap[child] )) && break
    tmp=${heap[$parent]}; heap[$parent]=${heap[$child]}; heap[$child]=$tmp
    parent=$child
  done
}
heap=()
for value in 5 1 9 3 7 2; do heap_insert "$value"; if (( ${#heap[@]} > 3 )); then heap_pop; fi; done
list_string 9 7 5; echo

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