问题
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?
回答1:
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.
回答2:
This can be done at compile time with this code (keep in mind you need latest GCC or Clang, won't work in MSVC2k12 at this time). It makes it compile slow but it is instant at run-time.
#include <iostream>
constexpr int array[10] = { 1, 0, 2, 3, 0, 2, 7, 1, 9, 2 };
template<int maxest, int index>
struct find_biggest_r {
enum { value = find_biggest_r<(array[index] > maxest ? array[index]:maxest),index-1>::value };
};
template<int maxest>
struct find_biggest_r<maxest,0> {
enum { value = (array[0] > maxest ? array[0] : maxest) };
};
template<int index>
struct find_biggest {
enum { value = find_biggest_r<array[index-1],index-2>::value };
};
int main()
{
std::cout << find_biggest<10>::value;
}
EDIT: Sorry this was for just the largest. For the kth largest, I need to add an argument or two, I will do it later today.
来源:https://stackoverflow.com/questions/11412023/which-is-the-fastest-algorthm-for-selecting-kth-largest-number-in-an-unsorted-ar