【算法】第 n 小数 nth_element
2014-04-30 16:48
295 查看
STL 中取第 n 小数的算法 nth_element 的函数原型如下
算法说明:
1、功能:执行 nth_element 后,nth 所指位置的元素将是整个区间有序时在该处的元素。对 [first, nth) 中的任意迭代器 i 和 [nth, last) 中的任意迭代器 j,满足 !(*i > *j)。
2、要求:RandomAccessIterator 必须满足 ValueSwappable。*first 的类型必须满足 MoveConstructible 和 MoveAssignable。
3、复杂度:平均为线性。
源码如下:
其中的
unguarded_partition,
median 和 insertion_sort 在之前介绍过,这里不再列出它们的源码。其中的 Type 由 RandomAccessIterator 的 traits 得到,这里简化了。函数中的 first 和 last 可能改变,当 [first, last) 区间大于3时就一直划分,划分是采用三者取中的方式以缓解输入时的糟糕情况,每次划分后产生两段,若右段起点
cut <= nth,则再对右段划分,否则对左段划分。直到区间长度小于等于3时,索性对这个小区间进行插入排序,注意 nth 始终在 [first, last) 中。
template<class RandomAccessIterator> void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last);
算法说明:
1、功能:执行 nth_element 后,nth 所指位置的元素将是整个区间有序时在该处的元素。对 [first, nth) 中的任意迭代器 i 和 [nth, last) 中的任意迭代器 j,满足 !(*i > *j)。
2、要求:RandomAccessIterator 必须满足 ValueSwappable。*first 的类型必须满足 MoveConstructible 和 MoveAssignable。
3、复杂度:平均为线性。
源码如下:
template <class RandomAccessIterator> void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last) { while (last - first > 3) { RandomAccessIterator cut = unguarded_partition(first, last, Type(median( *first, *(first + (last - first) / 2), *(last - 1)))); if (cut <= nth) { first = cut; } else { last = cut; } } insertion_sort(first, last); }
其中的
unguarded_partition,
median 和 insertion_sort 在之前介绍过,这里不再列出它们的源码。其中的 Type 由 RandomAccessIterator 的 traits 得到,这里简化了。函数中的 first 和 last 可能改变,当 [first, last) 区间大于3时就一直划分,划分是采用三者取中的方式以缓解输入时的糟糕情况,每次划分后产生两段,若右段起点
cut <= nth,则再对右段划分,否则对左段划分。直到区间长度小于等于3时,索性对这个小区间进行插入排序,注意 nth 始终在 [first, last) 中。
相关文章推荐
- PB6.5调用Web Service的办法
- cocos2d-x3.0 PageView
- 用C#实现C/S模式下软件自动在线升级
- SpringMVC同名参数属性简单解决方案obj.property
- 黑马程序员-Java文件复制代码
- 定制您的“微信/来往/易信和微博”的原创内容
- SqlServer_批量替换某字段值所包含的某字符串;
- Windows下安装Hadoop
- 插件
- object c @synthesize 自动生成setter,getter方法
- 多边形重心问题
- jquery扩展例子
- 软考倒计时24天:熟记点
- C++的那些事:表达式与语句
- 我就马上,你,美女,美女
- CentOS 防火墙配置 80端口
- 一种使用QThread线程的新方法QObject::moveToThread
- 【超详细科普贴】wifi共享精灵抢先版怎么用?
- win32 字体变换与窗口同大同小
- Daily English words study