Possible Duplicate:
How to find the kth largest element in an unsorted array of length n in O(n)?
The number of elements can vary from 1 to 10 million .Which is the fastest selection algorithm available for this purpose? Please note I think data structures like AVL Trees won’t work here due to duplication of array elements?
A selection algorithm can run in O(N) time.
The most general way is to make a pass through the array, keep the K largest numbers you’ve seen so far. Return the last element of that list. As @ChrisA points out in the comments
std::nth_element(documented here) is the quickest way to use this approach.If you always want the top Kth largest items (and data is changed sometimes), then consider storing the data in a heap. This is more expensive, but gives you a “live” structure of the data.