Why it matters
Partial sort beats full sort for top-K. Understanding shapes efficient top-K.
Advertisement
The architecture
Build max-heap of first K.
For each remaining: if smaller than root, replace + heapify.
Sort the K.
Advertisement
How it works end to end
Heap-based: O(n log k).
Quickselect + sort: O(n + k log k).
Use heap when k << n.