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.

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 = "")

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