It seems not neccessary to have a separate sort step.
You can do this:
- First take N elements from the begining of the unsorted array, and form a new array.
- Sort the new array, which would be much fast, assuming N is much smaller than the original array size.
- Go thru the rest array element in the original array, insert a element into the sorted array, if it is smaller than the largest element of the new array, and does not exist in the new array, and also get rid of the largest element in the new array.
- This algorithm goes thru the entire original array, but only for comparing, and most of the time, no extra effort (inserting) other than comparing is needed.
(strike out per adrianh
If you are willing to spend a little bit more effort, then I sugegst this improvement:
In step 3, instead of going thru the entire original array, you can chop the original array into pieces, say each piece contains 10 * N element (tweak with this 10, it could be 5, could be 50...). Sort each piece (we are sorting some smaller arrays), then only take the first N elements of the sorted piece, and go thru them.