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.
Ruby DSA Implementation
basic.rb
def list_string(values) = "[#{values.join(', ')}]"
def heap_insert(heap, value)
heap << value
child = heap.length - 1
while child > 0
parent = (child - 1) / 2
break if heap[parent] <= heap[child]
heap[parent], heap[child] = heap[child], heap[parent]
child = parent
end
end
def heap_pop(heap)
smallest = heap[0]
heap[0] = heap.pop
parent = 0
loop do
left = parent * 2 + 1
right = left + 1
break if left >= heap.length
child = right < heap.length && heap[right] < heap[left] ? right : left
break if heap[parent] <= heap[child]
heap[parent], heap[child] = heap[child], heap[parent]
parent = child
end
smallest
end
heap = []
[5, 1, 9, 3, 7, 2].each do |value|
heap_insert(heap, value)
heap_pop(heap) if heap.length > 3
end
puts list_string(heap.sort.reverse)
Implementation notes
- The working heap is a Ruby
Arrayused as a min-heap, starting fromheap = []. - This page reuses
heap_insertandheap_pop; both mutate the same heap array in place. - The input values are fixed as
[5, 1, 9, 3, 7, 2], and the size bound is the literal3. - Each value is inserted first with
heap_insert(heap, value). - Immediately after insertion,
heap_pop(heap) if heap.length > 3removes the current minimum whenever the heap grows past the top-k size. - That means small values can enter briefly; the trace for value
2ends back at[5, 7, 9]after trimming. - The replayed heap states are
[5],[1, 5],[1, 5, 9],[3, 5, 9],[5, 7, 9], then[5, 7, 9]. - The heap array itself is not descending sorted, so output uses
heap.sort.reverseonly for display. list_string(heap.sort.reverse)prints the final top values as[9, 7, 5].
Output
[9, 7, 5]