算法导论第7章—快速排序

快速排序

#include<iostream>
using namespace std;

void Print(int *A,int p,int r){
	for(int i=p;i<=r;i++)
		cout<<A[i]<<" ";
	cout<<endl;
}

int Partition(int *A,int p,int r){
	int x=A[r];
	int i=p-1;
	for(int j=p;j<=r-1;j++){
		if(A[j]<=x){
			i++;
			swap(A[i],A[j]);
		}
	}
	swap(A[i+1],A[r]);
	return i+1;
}

void QuickSort(int *A,int p,int r){
	if(p<r){
		int q=Partition(A,p,r);
		QuickSort(A,p,q-1);
		QuickSort(A,q+1,r);
	}
}

int main(){
	int A[100];
	int p,r;
	cout<<"请输入p,q的值:";
	cin>>p>>r;
	cout<<"请输入数字:";
	for(int i=p;i<=r;i++)
		cin>>A[i];
	cout<<"快速排序前:";
	Print(A,p,r);
	cout<<"快速排序后:";
	QuickSort(A,p,r);
	Print(A,p,r);
	return 0;
}

随机化版本:

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

void Print(int *A,int p,int r){
	for(int i=p;i<=r;i++)
		cout<<A[i]<<" ";
	cout<<endl;
}

int Partition(int *A,int p,int r){
	int x=A[r];
	int i=p-1;
	for(int j=p;j<=r-1;j++){
		if(A[j]<=x){
			i++;
			swap(A[i],A[j]);
		}
	}
	swap(A[i+1],A[r]);
	return i+1;
}

int Randomized_Partition(int *A,int p,int r){
	srand(time(NULL));    //生成随机数
	int i=rand()%(r-p)+p;
	swap(A[r],A[i]);
	return Partition(A,p,r);
}
void Randomized_QuickSort(int *A,int p,int r){
	if(p<r){
		int q=Randomized_Partition(A,p,r);
		Randomized_QuickSort(A,p,q-1);
		Randomized_QuickSort(A,q+1,r);
	}
}

int main(){
	int A[100];
	int p,r;
	cout<<"请输入p,q的值:";
	cin>>p>>r;
	cout<<"请输入数字:";
	for(int i=p;i<=r;i++)
		cin>>A[i];
	cout<<"快速排序前:";
	Print(A,p,r);	
	Randomized_QuickSort(A,p,r);
	cout<<"快速排序后:";
	Print(A,p,r);
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值