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.
Complexity
- Time: O(n log k)
- Space: O(k)
bounded heap
For top-k largest values, a min-heap of size k keeps the current cutoff at the root.
R DSA Implementation
basic.R
list_string <- function(values) paste0("[", paste(values, collapse = ", "), "]")
heap_insert <- function(heap, value) {
heap <- c(heap, value)
child <- length(heap)
while (child > 1) {
parent <- floor(child / 2)
if (heap[parent] <= heap[child]) break
tmp <- heap[parent]; heap[parent] <- heap[child]; heap[child] <- tmp
child <- parent
}
heap
}
heap_pop <- function(heap) {
smallest <- heap[1]
heap[1] <- heap[length(heap)]
heap <- heap[-length(heap)]
parent <- 1
while (TRUE) {
left <- parent * 2
right <- left + 1
if (left > length(heap)) break
child <- left
if (right <= length(heap) && heap[right] < heap[left]) child <- right
if (heap[parent] <= heap[child]) break
tmp <- heap[parent]; heap[parent] <- heap[child]; heap[child] <- tmp
parent <- child
}
list(value = smallest, heap = heap)
}
heap <- c()
for (value in c(5, 1, 9, 3, 7, 2)) { heap <- heap_insert(heap, value); if (length(heap) > 3) heap <- heap_pop(heap)$heap }
cat(list_string(sort(heap, decreasing = TRUE)), "\n", sep = "")
Implementation notes
heap <- c()starts an empty R vector used as the min-heap.- The loop processes the pinned values
c(5, 1, 9, 3, 7, 2)in that order. - Each value first goes through
heap <- heap_insert(heap, value), using the same vector-backed insert and sift-up helper as the heap insert lesson. if (length(heap) > 3) heap <- heap_pop(heap)$heapkeeps onlyk = 3values.heap_pop()returns a list, and$heapselects the remaining heap after the current smallest cutoff has been removed.- After
3,7, and2, the heap temporarily grows past size3, so the current smallest value is popped back out.
Replay steps
5 -> [5]
1 -> [1, 5]
9 -> [1, 5, 9]
3 -> [3, 5, 9]
7 -> [5, 7, 9]
2 -> [5, 7, 9]
[5, 7, 9]is a min-heap shape, not display order.- For output,
sort(heap, decreasing = TRUE)turns it into[9, 7, 5]. list_string(...)andcat(..., "\n", sep = "")print exactly[9, 7, 5].
Output
[9, 7, 5]