Here are some ideas that you can explore on. I am not giving away the solution yet.
Solution for a more general problem :
Search for Kth order statistic. Expected average case runtime is O(n).
Then its just a matter of another loop to partition the elements greater than that statistic and less than the statistic. Something like the partitioning algorithm of Quicksort.
So overall complexity is still O(n).
Now your question talks about cost finding 5 best elements :
This has nothing to do with complexity. There are varied approaches one can follow :
What if you wanted the top 2 elements :
One of the most effective approaches will be to maintain 2 variables largest
and second_largest
and update them with a single run of a loop.
int a[] = {1,2,3,4,5,6,6,78,567,5675673,345242,234,231,12,12,50};
int largest = -1,second_largest = -1; // Let's assume numbers are positive. It doesn't matter.
for (int i=0;i<N;i++)
if (a[i] > largest)
{
second_largest = largest;
largest = a[i];
}
else if (a[i] > second_largest)
second_largest = a[i];
Now as you want top - 5 elements you can still do the same. Maybe this might prove to be the best in terms of cycle-accurate run-time.
Another approach is to maintain a Heap Data Structure. There are some interesting ways to solve your problem using heaps. (Again I am not giving away much)
Last comments : This kind of approach is used in mobile phone contact directories, where as soon as you open they have to show you some top - X contacts in some order. So there are a bunch of research papers also on this.
Very interesting how a simple problem can lead to some complicated solutions when applied to real life !
I hope you enjoyed reading and explore on your own to find what's the best for you.