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.