利用中位数进行快速排序
2014-01-14 21:23
405 查看
#include <iostream> #include <ctime> #include <boost/timer/timer.hpp> using namespace boost::timer; using namespace std; int partition(int *a,int low,int high)//快速排序分割 { int key=a[high]; int p=low-1; int tmp; for(int i=low;i<high;++i){ if(a[i]<=key){ p++; tmp=a[i]; a[i]=a[p]; a[p]=tmp; } } tmp=a[p+1]; a[p+1]=key; a[high]=tmp; /*for(int i=low;i<=high;i++){ cout<<a[i]<<"\t"; } cout<<endl;*/ return p+1; } int random_partition(int *a,int low,int high)//随机化快速排序 { int rnd=rand()%(high-low+1)+low;//随机生成 int tmp=a[high]; a[high]=a[rnd]; a[rnd]=tmp; return partition(a,low,high); } int random_select(int *a,int low,int high,int index)//找出第index个最小元素 { if(low == high){ return a[low]; } int p=random_partition(a,low,high); /*for(int i=low;i<=high;i++){ cout<<a[i]<<"\t"; } cout<<endl;*/ //int k=p; //int p=partition(a,low,high); if(p==index) return a[p]; else if(p<index){ return random_select(a,p+1,high,index); }else{ return random_select(a,low,p-1,index); } } void best_case_quicksort(int *a,int low,int high) { if(low<high){ int index=((low+high)>>1); random_select(a,low,high,index);//取中位数 //int q = partition(a,low,high); best_case_quicksort(a,low,index-1); best_case_quicksort(a,index+1,high); } } void naive_quicksort(int *a,int low,int high) { if(low<high){ int q = partition(a,low,high); naive_quicksort(a,low,q-1); naive_quicksort(a,q+1,high); } } int main() { srand((unsigned)time(NULL)); int count; while (count=rand()%10,count<3); count=10000000; int *a=new int[count]; int *b=new int[count]; for(int i=0;i<count;++i){ a[i]=rand()%10000001-5000000; b[i]=a[i]; //cout<<a[i]<<"\t"; } cout<<endl; cpu_timer t1; t1.start(); naive_quicksort(a,0,count-1); t1.stop(); cout<<t1.format(); ////for(int i=0;i<count;i++){ //// cout<<a[i]<<"\t"; ////} ////cout<<endl; cpu_timer t2; t2.start(); best_case_quicksort(b,0,count-1); t2.stop(); /*for(int i=0;i<count;++i){ cout<<b[i]<<"\t"; } cout<<endl;*/ cout<<t2.format(); delete[]a; delete[]b; }
相关文章推荐
- .net3.5下利用Linq新特性对Dictionary进行快速排序
- 利用快速排序的子程序查找中位数
- 【c语言】利用库函数进行快速排序(升)
- 利用随机化的思想对快速排序进行优化
- 利用系统函数qsort()进行快速排序的七种形式
- 利用快速排序对单链表进行排序
- 利用内存寻址进行快速排序的算法
- 利用fprintf进行文件操作--向文件中追加写入
- mapreduce 利用InverseMapper.class对key,value进行 交换实现词频排序
- 【转】利用JMeter进行压力测试
- 通过Last-Modified,Etag利用客户端缓存对网站进行优化?
- 如何利用客户端缓存对网站进行优化?
- 利用序列化进行深度克隆
- caffe学习(二):利用mnist数据集训练并进行手写数字识别(windows)
- 利用fetch进行POST传参
- BTV1重播法制进行时,利用木马攻击勒索14万换来6年铁窗
- C/S中利用域控进行SSO的简单实现方式
- 利用Python进行数据分析(13) pandas基础: 数据重塑/轴向旋转
- 利用runtime进行归档/解归档
- Atitit 如何利用先有索引项进行查询性能优化