nth_element()是c++的STL库中的函数,作用是将数组中第k小的整数放在区间第k个位置
比如a[6]={2,5,6,4,7,8},使用nth_element(a,a+3,a+6)后,区间中第四个数,也就是a[3],会被放入数组中第四小的数,也就是6( a a a的下标是从0开始的)。
使用一次nth_element()的时间复杂度为 O ( n ) O(n) O(n)
code
#include<bits/stdc++.h>
using namespace std;
int a[6]={2,5,6,4,7,8};
int main()
{
nth_element(a,a+3,a+6);
for(int i=0;i<6;i++){
printf("%d ",a[i]);
}
return 0;
}
输出:
5 2 4 6 7 8
如果a数组不从0开始,则需做一些调整
code
#include<bits/stdc++.h>
using namespace std;
int n,k,b[15];
int main()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf("%d",&b[i]);
}
nth_element(b+1,b+k,b+n+1);
for(int i=1;i<=n;i++){
printf("%d ",b[i]);
}
printf("\n");
printf("%d",b[k]);
return 0;
}
输入:
8 4
7 5 3 8 4 6 2 9
输出:
3 2 4 5 8 6 7 9
5