python快排递归非递归

  • 递归形式如下:
alist = [3,1,2,9,0,7,4,8,5,6]

def quickSort(alist,start,end):
    if start >= end:
        return
    index = start
    privior = alist[index]
    low = start
    hight = end
    #这个while跑完之后,alist[start]就是provior,start左边的都比privior小,右边的都比privior大
    while low < hight:
         #在高位找出一个比privior小的数字,必须先写高位hight,然后再写低位的low
        while alist[hight] >= privior and low < hight :
            hight = hight - 1
        #在低位找出一个比privior大的数字
        while alist[low] <= privior and low < hight :
            low = low + 1
        #两者交换
        if low < hight:
            temp = alist[low]
            alist[low] = alist[hight]
            alist[hight] = temp

    alist[index] = alist[low]
    alist[low] = privior
    
    quickSort(alist,start,low)
    quickSort(alist,low+1,end)

if __name__ == '__main__':
    quickSort(alist,0,9)
    astr = ''
    for item in alist:
        astr = astr + str(item)
        astr = astr + ' '
    
    print(astr)
        
  • 非递归的形式如下:
alist = [3,1,2,9,0,7,4,8,5,6]

def qs(alist,start,end):
    if start >= end:
        return
    
    indexList = []
    indexList.append(start)
    indexList.append(end)

    #判断条件是栈非空
    while len(indexList) > 0:
        priviorIndex = indexList[0]
        privior = alist[indexList[0]]
        low = indexList[0]
        hight = indexList[1]

        while low < hight:
            
            #必须先写右边的,没办法的.否则hight的值会被冲掉,这是代码的问题
            while alist[hight] >= privior and low < hight:
                hight = hight - 1
            while alist[low] <= privior and low < hight:
                low = low + 1
            
            #满足交换条件
            if low < hight:
                temp = alist[low]
                alist[low] = alist[hight]
                alist[hight] = temp
        
        alist[priviorIndex] = alist[low]
        alist[low] = privior

        #其实使用递归的时候,可见其保存的现场就是三个东西,alist,下一步快排的左边界,下一步快排的右边界,
        # 我们只需要手工保存这几个现场,并且在必要的时候弹出栈即可,下面的两个if就是保存现场
        if low > indexList[0]:
            indexList.append(indexList[0])
            indexList.append(low)
        
        if hight < indexList[1]:
            indexList.append(low + 1)
            indexList.append(indexList[1])
        
        #这里就是弹出栈的代码
        indexList.pop(0)
        indexList.pop(0)



if __name__ == '__main__':
    qs(alist,0,9)
    astr = ''
    for item in alist:
        astr = astr + str(item)
        astr = astr + ' '
    
    print(astr)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值