08-heaps
Top-K with a Heap
Keep only the largest k values by maintaining a small min-heap.
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.
bounded heap
For top-k largest values, a min-heap of size k keeps the current cutoff at the root.
Complexity
- Time: O(n log k)
- Space: O(k)
Bash DSA Implementation
basic.sh
Replay: real traced execution (multi-file project)
#!/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
top-k heap ← [5]
3local joined=""4for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5printf '[%s]' "$joined"values this step[5]top-k heap5valuetop-k heap ← [1, 5]
3local joined=""4for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5printf '[%s]' "$joined"values this step[1, 5]top-k heap1valuetop-k heap ← [1, 5, 9]
3local joined=""4for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5printf '[%s]' "$joined"values this step[1, 5, 9]top-k heap9valuetop-k heap ← [3, 5, 9]
3local joined=""4for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5printf '[%s]' "$joined"values this step[3, 5, 9]top-k heap3valuetop-k heap ← [5, 7, 9]
3local joined=""4for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5printf '[%s]' "$joined"values this step[5, 7, 9]top-k heap7valuetop-k heap ← [5, 7, 9]
3local joined=""4for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5printf '[%s]' "$joined"values this step[5, 7, 9]top-k heap2valuestdout ← [9, 7, 5]
4 for value in "$@"; do [[ -n "$joined" ]] && joined+=", "; joined+="$value"; done5 printf '[%s]' "$joined"6}values this step[9, 7, 5]stdout[5, 7, 9]top-k heap
Output
[9, 7, 5]