利用中位数进行快速排序

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值