您可以使用快速排序算法的基础来执行您所需的操作,除了重新排序分区外,您可以摆脱掉期望范围内的条目。
它被称为 “快速选择” 和here is a C++ implementation:
int partition(int* input, int p, int r)
{
int pivot = input[r];
while (p < r)
{
while (input[p] < pivot)
p++;
while (input[r] > pivot)
r--;
if (input[p] == input[r])
p++;
else if (p < r) {
int tmp = input[p];
input[p] = input[r];
input[r] = tmp;
}
}
return r;
}
int quick_select(int* input, int p, int r, int k)
{
if (p == r) return input[p];
int j = partition(input, p, r);
int length = j - p + 1;
if (length == k) return input[j];
else if (k < length) return quick_select(input, p, j - 1, k);
else return quick_select(input, j + 1, r, k - length);
}
int main()
{
int A1[] = { 100, 400, 300, 500, 200 };
cout << "1st order element " << quick_select(A1, 0, 4, 1) << endl;
int A2[] = { 100, 400, 300, 500, 200 };
cout << "2nd order element " << quick_select(A2, 0, 4, 2) << endl;
int A3[] = { 100, 400, 300, 500, 200 };
cout << "3rd order element " << quick_select(A3, 0, 4, 3) << endl;
int A4[] = { 100, 400, 300, 500, 200 };
cout << "4th order element " << quick_select(A4, 0, 4, 4) << endl;
int A5[] = { 100, 400, 300, 500, 200 };
cout << "5th order element " << quick_select(A5, 0, 4, 5) << endl;
}
OUTPUT:
1st order element 100
2nd order element 200
3rd order element 300
4th order element 400
5th order element 500
编辑
这个特定的实现有一个O(n)的平均运行时间;由于选择主键的方法,它共享快速排序的最坏情况运行时间。通过optimizing the pivot choice,你最坏的情况也会变成O(n)。
你可以修改矢量吗? nth_element将进行部分排序,因此它会修改向量。 – amdn 2013-02-15 23:28:38
可以修改向量,但最终结果需要是k个最大元素的索引(原始向量的索引)。 – hazelnusse 2013-02-16 02:19:37
这只是一个选择算法。通常你会使用堆选择或快速选择。有关类似问题,请参阅http://stackoverflow.com/q/7746648/56778。有一个好的C++解决方案的答案。 (使用priority_queue) – 2013-02-20 20:47:15