nth_element() O(n)复杂度求第k+1小元素
函数原型
void nth_element(_RAIter, _RAIter, _RAIter);
void nth_element(_RAIter, _RAIter, _RAIter, _Compare);
void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth,
_RandomAccessIterator __last)
void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth,
_RandomAccessIterator __last, _Compare __comp)
先看官方的声明
void nth_element(_RAIter, _RAIter, _RAIter);
/*
@brief Sort a sequence just enough to find a particular position
using a predicate for comparison.
@ingroup sorting_algorithms
@param __first An iterator.
@param __nth Another iterator.
@param __last Another iterator.
@param __comp A comparison functor.
@return Nothing.
Rearranges the elements in the range @p [__first,__last) so that @p *__nth is the same element that would have been in that position had the whole sequence been sorted. The elements either side of @p *__nth are not completely sorted, but for any iterator @e i in the range @p [__first,__nth) and any iterator @e j in the range @p [__nth,__last) it holds that @p__comp(*j,*i) is false.
*/
请注意这句话
so that @p *__nthis the same element that would have been in that position had the whole sequence been sorted.
函数作用后*_nth的位置的值 与 排序之后*nth的值相等
那么我们要求数组a中第k小的值,第二个参数就应该填a+k-1
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int a[]={1,5,6,7,50,0,3,6,98,4,6,57,17,71,2,100};
vector<int>aa(a,a+16);
sort(aa.begin(),aa.end());
for(auto i:aa)
cout<<i<<" ";
cout<<endl;
nth_element(a,a+10,a+16);//a[10]的位置的值是排序之后a[10]的值 即第10+1小的位置
for(auto i:a)
cout<<i<<" ";
cout<<endl;
}
或者可以写成一个函数
#include<algorithm>
#include<iostream>
using namespace std;
int GetNthVal(int *first,int *last,int k)/*第一小是最小,作用:求[first,last)中第k小的值*/
{
if(k>last-first)
return -1;
nth_element(first,first+k-1,last);
return first[k-1];
}
int main()
{
int a[]={1,5,6,7,50,0,3,6,98,4,6,57,17,71,2,100};
vector<int>aa(a,a+16);
sort(aa.begin(),aa.end());
for(auto i:aa)
cout<<i<<" ";
cout<<endl;
cout<<GetNthVal(a,a+16,15);//求数组a中 第15小的值
}