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.

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)$heap keeps only k = 3 values.
  • heap_pop() returns a list, and $heap selects the remaining heap after the current smallest cutoff has been removed.
  • After 3, 7, and 2, the heap temporarily grows past size 3, 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(...) and cat(..., "\n", sep = "") print exactly [9, 7, 5].

Output

[9, 7, 5]