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.
C# DSA Implementation
basic.cs
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static string ListString(IEnumerable<int> values) => "[" + string.Join(", ", values) + "]";
static void HeapInsert(List<int> heap, int value) {
heap.Add(value);
int child = heap.Count - 1;
while (child > 0) {
int parent = (child - 1) / 2;
if (heap[parent] <= heap[child]) break;
(heap[parent], heap[child]) = (heap[child], heap[parent]);
child = parent;
}
}
static int HeapPop(List<int> heap) {
int smallest = heap[0];
heap[0] = heap[^1];
heap.RemoveAt(heap.Count - 1);
int parent = 0;
while (true) {
int left = parent * 2 + 1, right = left + 1;
if (left >= heap.Count) break;
int child = left;
if (right < heap.Count && heap[right] < heap[left]) child = right;
if (heap[parent] <= heap[child]) break;
(heap[parent], heap[child]) = (heap[child], heap[parent]);
parent = child;
}
return smallest;
}
static void Main() { var heap = new List<int>(); foreach (var value in new[] {5, 1, 9, 3, 7, 2}) { HeapInsert(heap, value); if (heap.Count > 3) HeapPop(heap); } heap.Sort((a, b) => b.CompareTo(a)); Console.WriteLine(ListString(heap)); }
}
@end @output [9, 7, 5] @end