给定随机数列求第k大的数字

原来STL我还是有很多不知道的地方

STL 采用的算法是: 当数组长度 <= 3时, 采用插入排序。
当长度 > 3时, 采用快排 Partition 的思想,也就是说类似快速排序(这里不妨假设是降序排列);

快排Partition思想,随机选择一个分界点,进行一次划分。划分结束后,考察划分点现在的位置i:
如果待求的第k大在划分点后面,那么在a[i+1:len(a)]子序列中寻找第k-i-1大的数字;
如果待求点在划分点前面,那么在a[0:i-1]子序列中寻找第k大的数字
如果正好i=k,返回就完了

#include<iostream>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int main(){
	int a[10];
	for (int i = 0; i < 10; i++){
		a[i] = rand();
		cout << a[i] << " ";
	}
	puts("");
	nth_element(a, a + 3, a + 10);
	cout << a[3] << endl;
	return 0;
}
原文地址:https://www.cnblogs.com/weiyinfu/p/6637492.html