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.
Java DSA Implementation
Basic.java
import java.util.*;
class Basic {
static String listString(List<Integer> values) { return values.toString(); }
static void heapInsert(List<Integer> heap, int value) {
heap.add(value);
int child = heap.size() - 1;
while (child > 0) {
int parent = (child - 1) / 2;
if (heap.get(parent) <= heap.get(child)) break;
Collections.swap(heap, parent, child);
child = parent;
}
}
static int heapPop(List<Integer> heap) {
int smallest = heap.get(0);
heap.set(0, heap.remove(heap.size() - 1));
int parent = 0;
while (true) {
int left = parent * 2 + 1;
int right = left + 1;
if (left >= heap.size()) break;
int child = left;
if (right < heap.size() && heap.get(right) < heap.get(left)) child = right;
if (heap.get(parent) <= heap.get(child)) break;
Collections.swap(heap, parent, child);
parent = child;
}
return smallest;
}
public static void main(String[] args) { List<Integer> heap = new ArrayList<>(); for (int value : new int[] {5, 1, 9, 3, 7, 2}) { heapInsert(heap, value); if (heap.size() > 3) heapPop(heap); } heap.sort(Collections.reverseOrder()); System.out.println(listString(heap)); }
}
@end @output [9, 7, 5] @end