Data Structures & Algorithms / Module 7: Heaps
Topic 7.2
Top-K and heap sort
The K largest of a stream without storing it all, and heap sort.
Watch: the number on top of the small pile is the entry bar. Any new number below it is skipped straight away.
- moving now
- being checked
- finished / the result
- no longer used
Why a min-heap to find the largest
It sounds backwards, but it makes sense. Picture a top-10 leaderboard. What you compare a new score against is 10th place, the weakest of the top 10. If the new score doesn't beat it, it's out. A min-heap keeps that weakest one on top, ready to compare in one step.
Code, for programmersThe K largest with a min-heap
// MinHeap from the previous topic
function topK(stream, k) {
const heap = new MinHeap();
for (const x of stream) {
if (heap.a.length < k) heap.push(x);
else if (x > heap.peek()) { // beats the weakest of the top k
heap.pop();
heap.push(x);
} // otherwise: one comparison, then skip
}
return heap.a.sort((a, b) => b - a);
}Compared with sorting everything
| Approach | Time | Memory |
|---|---|---|
| Sort everything, take the first K | O(n log n) | O(n) |
| Min-heap of K | O(n log K) | O(K) |
The time is similar when K is large. The difference you really feel is memory: the heap never holds all the data. That's why this suits streams that never stop, like request logs, where you can't "sort everything" because the data keeps coming.
Heap sort
Turn the whole array into a max-heap (doable in place in O(n)), then repeatedly swap the top with the last element and shrink the heap by one. The largest pile up at the back in order. That's O(n log n) in the worst case with no extra memory, but it isn't stable, and in practice it's slower than quick sort because it jumps around in memory. It's used as the fallback in introsort when quick sort starts going badly.
Quiz
To find the 10 largest numbers, which heap do you keep?
A billion rows, K = 100. How much memory does the heap need?
What is heap sort's drawback compared with merge sort?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.