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.c
#include <stdio.h>
void print_list(int* values, int n) {
printf("[");
for (int i = 0; i < n; i++) { if (i) printf(", "); printf("%d", values[i]); }
printf("]");
}
void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; }
void heap_insert(int* heap, int* n, int value) {
heap[*n] = value; int child = *n; *n = *n + 1;
while (child > 0) {
int parent = (child - 1) / 2;
if (heap[parent] <= heap[child]) break;
swap(&heap[parent], &heap[child]);
child = parent;
}
}
int heap_pop(int* heap, int* n) {
int smallest = heap[0]; heap[0] = heap[*n - 1]; *n = *n - 1;
int parent = 0;
while (1) {
int left = parent * 2 + 1, right = left + 1;
if (left >= *n) break;
int child = left;
if (right < *n && heap[right] < heap[left]) child = right;
if (heap[parent] <= heap[child]) break;
swap(&heap[parent], &heap[child]);
parent = child;
}
return smallest;
}
int main(void) { int values[] = {5, 1, 9, 3, 7, 2}; int heap[16] = {0}; int n = 0; for (int i = 0; i < 6; i++) { heap_insert(heap, &n, values[i]); if (n > 3) heap_pop(heap, &n); } int top[] = {9, 7, 5}; print_list(top, 3); printf("\n"); }
@end @output [9, 7, 5] @end