快速排序的两种方法(python、c++)

简述快速排序

  • 快排主要分为挖空法和交换法

快排都是借助函数的递归实现的

1. 挖空法:

主要通过一个外部变量,将该位置的空间腾出来用于之后不满足元素的存放,左右依次交换.
主要思想是通过递归的划分实现问题分解,每次函数查找的是某个目标元素(一般使用的是当前左侧的第一个元素)的实际位置

void quicksort(vector<int> &op,int left,int right){
	if(left>right)return;
	int a=left,b=right,temp=op[left];
	while(a<b){
			while(a<b&&op[b]>=temp)b--;
			op[a]=op[b];
			while(a<b&&op[a]<=temp)a++;
			op[b]=op[a];
		}
	op[a]=temp;//当前面循环结束时找到了temp元素的实际位置,直接填空
	quicksort(op,left,a-1);
	quicksort(op,a+1,right);
}
#python
#<=
def quicksort(op,left,right):
	if(left>right): return
	a=left
	b=right
	temp=op[left]
	while a<b:
		while a<b and op[b]>=temp:
		    b-=1
		op[a]=op[b]
		while a<b and op[a]<=temp:
		    a+=1
		op[b]=op[a]
	op[a]=temp
	quicksort(op,left,a-1)
	quicksort(op,a+1,right)  

#>=
def quicksort(op,left,right):
	if(left>right): return
	a=left
	b=right
	temp=op[left]
	while a<b:
		while a<b and op[b]>=temp:
		    b-=1
		op[a]=op[b]
		while a<b and op[a]<=temp:
		    a+=1
		op[b]=op[a]
	op[a]=temp
	quicksort(op,left,a-1)
	quicksort(op,a+1,right)
		

2. 交换法:

其实与挖空类似,只是这里每次找到一个当前不满足值时是直接与其反面(左侧/右侧)上次查找停止的位置交换元素

void quicksort(vector<int> &op,int left,int right){
	if(left>right)return;//注意这里,容易出错,只有当left>right 时其中的元素个数才为0  才不用继续向下继续进行
	int a=left,b=right,temp=op[left];
	while(a<b){
			while(a<b&&op[b]>=temp)b--;
			while(a<b&&op[a]<=temp)a++;
			if(a<b){
				int center=op[a];
				op[a]=op[b];
				op[b]=center;
			}
		}
	op[left]=op[a];//找到位置之后将此时这个位置的元素放到之前腾出位置的地方处
	op[a]=temp;
	quicksort(op,left,a-1);
	quicksort(op,a+1,right);
}

#python
def quicksort(op,left,right):
    if left>right: return
    a=left
    b=right
    temp=op[left]
    while a<b:
        while(a<b and op[b]>=temp): b-=1
        while(a<b and op[a]<=temp): a+=1
        if a<b:
            center=op[a]
            op[a]=op[b]
            op[b]=center
    op[left]=op[a]
    op[a]=temp
    quicksort(op,left,a-1)
    quicksort(op,a+1,right)
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

看不见的罗辑

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

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

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

打赏作者

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

抵扣说明:

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

余额充值