期望为线性时间的选择算法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也是一个随机算法。