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.

Partial sort flowMax-heap of Kfirst K elementsReplace rootif smallerSort heapfinal k sortedFor unsorted top-K: use heap or quickselect + sort
Partial sort.
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.