期望为线性时间的选择算法randomizedSelect
来源:互联网 发布:单片机多功能调试助手 编辑:程序博客网 时间:2024/04/27 16:41
一般选择算法看起来要比找最小值这样的简单问题更难,但有期望为线性时间的选择算法,期望运行时间为O(n)。
#include<iostream>#include<ctime>using namespace std;template<class T> int partition(T *a,int first,int end) //实现了对子数组A[p..r]的原址重排{int x = a[end-1];int i = first-1;for(int j=first;j<=end-1;++j){if(a[j-1] <= x){++i;swap(a[i-1],a[j-1]);}}swap(a[i],a[end-1]);return i+1;}template<class T>int randomizedPartition(T *a,int first,int end){ srand((unsigned)time(NULL)); int i = rand()%(end-first)+first;swap(a[i],a[end-1]);return partition(a,first,end);}template<class T>T randomizedSelect(T *a,int first,int end,int i) //返回数组A[first,end]中第i小的元素{if(first == end)return a[first-1];int q = randomizedPartition(a,first,end);int k = q-first+1;if(i==k) // the pivot value is the answerreturn a[q];else if(i<k)return randomizedSelect(a,first,q-1,i);elsereturn randomizedSelect(a,q+1,end,i-k);}template<class T>void print(T *a,int num) { for(int i=0;i<num;++i) cout<<a[i]<<ends; } int main() { int a[] ={5,2,4,6,1,8};//char a[]="HelloWorld!"; int num = sizeof(a)/sizeof(a[0]); cout<<randomizedSelect(a,1,num,3)<<endl; return 0; }
因为它的部分行为是由随机数生成器的输出决定的,所以randomizedSelect也是一个随机算法。
- 期望为线性时间的选择算法randomizedSelect
- 期望为线性时间的选择算法
- 期望时间为线性时间的选择算法(C++)
- 期望为线性时间选择算法
- Java 期望为线性时间的选择算法
- CLRS 9.2期望为线性时间的选择算法
- 期望为线性时间的选择算法(c语言)
- 选择问题的线性期望时间算法
- 期望为线性的选择算法
- 算法导论程序19-期望为线性时间的选择算法(Python)
- 小白进阶之期望为线性时间的选择算法
- 算法导论:第9章 中位数和顺序统计量_1期望为线性时间的选择算法
- 期待为线性时间的选择算法
- 期望线性时间选择
- 算法之分治——期望线性时间的选择(基础版本的选择)
- 算法--顺序统计-期望线性时间做选择
- 最坏情况为线性时间的选择算法
- CLRS 9.3最坏情况为线性时间的选择算法
- 【点滴积累】在C#中使用反射动态调用类型成员
- A Few Useful Things to Know about Machine Learning
- jdk1.6之ArrayList
- Hibernate
- 激光谐振腔稳定模式的Fox-Li迭代算法
- 期望为线性时间的选择算法randomizedSelect
- Hibernate
- 配置vim
- [Oracle] 数据库安全之 - 审计Audit
- NYOJ21 三个水杯
- gcc, as, ld的一些笔记
- 字符串转二进制和二进制转字符串:
- mybatis uncategorized SQLException for SQL []; SQL state [null]; error code [17004]; 无效的列类型
- jdk1.6之LinkedList