1 前言
近期学习K-D Tree,用到了nth_element,然而不是很确定具体的用法
然而,在网上搜索、点了几篇博客要么写的不是很清楚,要么干脆直接是错的
于是这篇博客用来记录我个人对nth_element的理解,希望能对你有所帮助,如果我自己忘了也能看这篇博客记起来
2 相关信息
2.1 所需头文件
#include<algorithm>
2.2 使用格式
有个一般式为:
nth_element(begin,nth,end,compare);
假设数组
的第1~m个位置有数,现在要求第n大
代码如下
nth_element(a+1,a+n,a+m+1,cmp);
要注意的是,使用
需要事先using namespace std或者加std::
即有两种选择(可以见后面的代码)
2.3 功能
对于一般的
我们是在
的时间复杂度内使数组内的元素有序,定义一个位置应该有的值为排完序之后这个位置上的值
而
的作用就是在
的时间复杂度内使得给定位置上的值成为这个位置该有的值(特殊的,在比较符号为小于并且起始位置为1的时候,做的是将数组中第n大的数放在n号位置)。
另外,
满足做完后,所有其他位置的值与给定位置的值的相对大小关系一定符合(当比较符号为小于的时候,相当于说比第n大的数小的数都放在第n大的数前面,比第n大的数大的数都放在第n大的数后面)(是不是说的很绕,可以看后面代码输出时候的解释)
2.3 实现
题目:输入n,k,以及n个数,求这n个数中第k大的值
我们可以用这个题来验证
的功能
#include<cstdio>
#include<algorithm>
//using namespace std;
int n,k,a[1000001];
int cmp(int a,int b){return a<b;}
int main()
{
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
std::nth_element(a+1,a+k,a+n+1);//开头的注释掉了,那么这个地方要用用了std::
for(int i=1;i<=n;i++)printf("%d ",a[i]);
return 0;
}
给出一组程序输入输出
你会发现,第3大的数3到了该去的位置,并且在3前面的数都比3小,在3后面的数都比3大
2.4 原理
众所周知,
主要的算法是快速排序
而
的本质上就是快速排序的一部分
给出快排代码
void sort(int*l,int*r)
{
if(l>=r)return;
swap(*l,*(l+rand()%(r-l)));
int *ll=l,*rr=r-1,v=*l;
while(ll<rr)
{
while(ll<rr&&(*rr)>=v)rr--;
*ll=*rr;
while(ll<rr&&(*ll)<=v)ll++;
*rr=*ll;
}
*ll=v;
sort(l,ll),sort(ll+1,r);
}
相当于是给定了上面代码的rand的值,然后不递归
由于太过简单,就不贴代码了
3 总结
容易发现,其实
并不难实现
但是STL的
速度尚可、使用方便
既然已经封装好了,不用白不用
学习一下使用方法能节省代码量