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.

9 min · intermediate

Watch: the number on top of the small pile is the entry bar. Any new number below it is skipped straight away.

streamheap (3)512319825114307
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 12

Find the 3 largest numbers in a stream, without storing them all. Keep a min-heap of 3: its top is the smallest of the 3 largest so far.

The heap's top is the 'entry bar'. Any number that doesn't clear it is skipped straight away.
K:

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

ApproachTimeMemory
Sort everything, take the first KO(n log n)O(n)
Min-heap of KO(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

  1. To find the 10 largest numbers, which heap do you keep?

  2. A billion rows, K = 100. How much memory does the heap need?

  3. What is heap sort's drawback compared with merge sort?

0 of 3 answered.