分治法之快速排序(以及快速排序的优化)(2021/1/24)

问题引入

快速排序以及其优化

代码实现

#include<iostream>
#include<cstdlib>
using namespace std;
struct Data{
	int flag;
};

//快速排序划分函数,返回基准元素最后的下标 
int Partition(struct Data*list,int low,int high){
	struct Data temp;
	int i=low,j=high,p=low;
	while(i<j){
		//从右向左
		while(j>i&&list[j].flag>list[p].flag){
			j--;
		}
		//进行元素交换
		if(j>i){ 
			temp=list[j];
			list[j]=list[i];
			list[i]=temp;
			p=j;
			i++; 
		} 
		//从左向右
		while(j>i&&list[i].flag<=list[p].flag){
			i++;
		} 
		//进行元素交换
		if(j>i){
			temp=list[i];
			list[i]=list[j];
			list[j]=temp;
			p=i;
			j--;
		} 
	} 
	return p;	
}

//快速排序递归函数
void QuickSort(struct Data*list,int low,int high){
	if(low<high){
		//进行划分
		int middle=Partition(list,low,high);
		//左部分快速排序
		QuickSort(list,low,middle-1);
		//右部分快速排序
		QuickSort(list,middle+1,high);	
	}
} 


//优化后的划分函数
//我们不用向左扫描,交换,向右扫描,交换
//我们完全可以向左扫描,向右扫描,然后交换 
int Partition_Pro(struct Data*list,int low,int high){
	struct Data temp;
	struct Data base=list[low];
	int i=low,j=high;
	while(i<j){
		//向左扫描
		while(i<j&&list[j].flag>base.flag){
			j--;
		} 
		//向右扫描
		while(i<j&&list[i].flag<=base.flag){
			i++;
		} 
		//交换
		if(i<j){
			temp=list[i];
			list[i]=list[j];
			list[j]=temp;
		}
	}
	//将基准元素放到正确位置
	if(list[i].flag>base.flag){//基准元素小于i,j的位置flag,则要将基准元素放在i-1位置 
		temp=list[i-1];
		list[i-1]=list[low];
		list[low]=temp;
		return i-1;
	}else{//交换i与low 
		temp=list[i];
		list[i]=list[low];
		list[low]=temp;
		return i;
	}
	
}

//快速排序Pro
void QuickSort_Pro(struct Data*list,int low,int high){
		if(low<high){
		//进行划分
		int middle=Partition(list,low,high);
		//左部分快速排序
		QuickSort(list,low,middle-1);
		//右部分快速排序
		QuickSort(list,middle+1,high);	
	}
} 

//测试函数
void Test(int method){
		struct Data list[10];
	//测试数据加载 
	for(int i=0;i<10;i++){
		if(i%2==0){
			list[i].flag=i*3;                                     
		}else{
			list[i].flag=i;
		}
	}
	cout<<"Test Data:";
	for(int i=0;i<10;++i){
		cout<<" "<<list[i].flag;
	}
	//进行快速排序 
	if(!method)
		QuickSort(list,0,9);
	else
		QuickSort_Pro(list,0,9);
	cout<<"\nUse QuickSort:";
	for(int i=0;i<10;++i){
		cout<<" "<<list[i].flag;
	}
	cout<<endl;
} 
int main(int argc,char** argv){
	Test(0);
	Test(1);
	return 0;
}

程序输出

Test Data: 0 1 6 3 12 5 18 7 24 9
Use QuickSort: 0 1 3 5 6 7 9 12 18 24
Test Data: 0 1 6 3 12 5 18 7 24 9
Use QuickSort: 0 1 3 5 6 7 9 12 18 24

--------------------------------
Process exited after 0.04895 seconds with return value 0
请按任意键继续. . .







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高万禄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值