没啥描述,,,
作用为求第n大的元素,并把它放在第n位置上,下标是从0開始计数的,也就是说求第0小的元素就是最小的数。
如:a[start,end]元素区间。排序后a[n]就是数列中第n+1大的数(下标从0開始计数)。要注意的是a[start,n),a[n,end]内的大小顺序还不一定。
仅仅能确定a[n]是数列中第n+1大的数。
当然a[start,n)中的数肯定不大于a[n,end]中的数。
注意:nth_element()函数不过将第n大的数排好了位置,并不返回值。
#include<bits/stdc++.h> using namespace std; inline int read(){ int x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if (ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = (x<<1) + (x<<3) + (ch^48); ch = getchar(); } return x * f; } int x[5000005]; int main(){ int t; t=read(); for(int i=0;i<t;++i){ int n,k; n=read(); k=read(); for(int i=0;i<n;++i){ x[i] = read(); } nth_element(x,x+k-1,x+n); cout<<x[k-1]<<endl; } system("pause"); return 0; }