Find the K largest (or smallest) elements in O(n log k) using a heap. Keep a min-heap of size K — anything bigger than the minimum gets swapped in.
What Is It?
To find the K largest elements, maintain a min-heap of size K. The smallest of your "top K" sits at the top of the heap. For each new element, if it's bigger than the heap's minimum, pop the min and push the new element. When you're done, the heap holds exactly the K largest elements.