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.
Python DSA Implementation
basic.py
def list_string(values):
return "[" + ", ".join(str(v) for v in values) + "]"
def heap_insert(heap, value):
heap.append(value)
child = len(heap) - 1
while child > 0:
parent = (child - 1) // 2
if heap[parent] <= heap[child]:
break
heap[parent], heap[child] = heap[child], heap[parent]
child = parent
def heap_pop(heap):
smallest = heap[0]
heap[0] = heap.pop()
parent = 0
while True:
left = parent * 2 + 1
right = left + 1
if left >= len(heap):
break
child = left
if right < len(heap) and heap[right] < heap[left]:
child = right
if heap[parent] <= heap[child]:
break
heap[parent], heap[child] = heap[child], heap[parent]
parent = child
return smallest
values = [5, 1, 9, 3, 7, 2]
heap = []
for value in values:
heap_insert(heap, value)
if len(heap) > 3:
heap_pop(heap)
print(list_string(sorted(heap, reverse=True)))
@end @output [9, 7, 5] @end