Just save the first, second, third.
first = array[0]; second = array[1]; third = array[2]; if(first < second) swap(first, second); if(first < third) swap(first, third); if(second < third) swap(second, third); for(i=3;i<N;i++) { if(third < array[i]) { third = array[i]; if(second < third) { swap(second, third); if(first < second) swap(first, second); } } }
I would not increase to k = four. I think three is a limitation for hard coding. As k increases, you need to move on to the formal method.
This does not answer the question that you actually asked, namely how to partially sort, but it seems that this is what you want.
If you want to partially sort, you can use quicksort and just return earlier when the axis is above the border that interests you. So, our first core is divided into five, two. Ignore the last two and actually do subtypes of the last five. But while it will be faster than quicksort, it will not be a change of game. If you can get a conservative upper bound for the k-th element (for example, it will always be no more than 25% between the minimum and average), you can quickly eliminate most of the data. If you are mistaken, this is just one pass or two.
Using the quicksort Method
int sortfirstk_r(int *array, int N, int k) { int pivot = 0; int j = n -1; int i = 1; while(i <= j) { if(array[pivot] < array[i]) swap(array[i], array[j--]) else i++; } sortfirstk_r(array, i, k < i ? k : i); if(i < k) sortfirstk_r(array +i, N -i, k - i); }
(Unchecked and there may be errors in the slightly complicated sorting logic).
However, we naively used the first element as a support. If we sort a large data set, and we have a normal distribution, and we want to get the top 1%, then the z-score is 2.326. Take a little more to give us some sampling error, and we will make the first pass with a rotary set, say 2.3 standard deviations above average. Then we divide the distribution into two sets: the top 1% plus a bit, and the rest. We do not need to further process the rest and just sort the top group.