The best way would be to use the common rank finding algorithm. Find the rank # of elements - k. In the step where k is found look to the right and those are the tops. O(n) time.
1
Anonymous
Jun 24, 2016
You could sort but there is a more efficient way. You could use a priority queue or have an array of length of k, copy the first k elements of the array, sort them and then read the rest of the elements of the original array and swap elements as necessary.