Which is the fastest algorthm for selecting kth largest number in an unsorted array containing non -unique elements? [duplicate]

时间秒杀一切 提交于 2020-01-06 19:59:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!