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. @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.
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)
@end @output [9, 7, 5] @end