Questions like "the k most frequent words" or "the k closest points" do not need the whole input sorted. A heap of size k processes the items in O(n log k), which is much faster when k is small. The trick is to use a min-heap to keep the k largest, so the weakest of your current top k is always ready to be thrown out. If k is close to n, simply sorting is just as good and simpler.