Worst case is O(n + k log n)