快速排序算法的两种python实现

快速排序算法在本例两种方法中涉及到函数的递归调用,细节处有些绕,需要理解调用的流程。
可能遇到的异常:
1、死循环;2、list index out of range;
解决思路:参数较多,可仔细检查参数使用是否出现混乱。
方法一:

# coding:utf-8
"""
起止下标:
:param begin, end:
前后游标:small, large
"""
def quickSort(listx, begin, end):
    if begin >= end:
        return
    small = begin
    large = end
    divide_val = listx[begin]
    while small < large:
        while small < large and listx[large] >= divide_val:
            large -= 1
        listx[small] = listx[large]

        while small < large and listx[small] < divide_val:
            small += 1
        listx[large] = listx[small]

    listx[small] = divide_val  #When the above loops is over, small==large
    #Or:
    #listx[large] = divide_val

    quickSort(listx, begin, large-1) #small == large
    quickSort(listx, large+1, end)

#功能测试:
if __name__ == "__main__":
    list = [95, 103, 52, 285, 29, 58, 208, 0, -1024, 2, 508]
    print(list)
    quickSort(list, 0, len(list)-1)
    print(list)

方法二:

# coding:utf-8

def quickSort(listx,start, end):
    if start < end:
        part = partition(listx, start, end)
        quickSort(listx, start, part)
        quickSort(listx, part+1, end)

def partition(listx, start, end):
    i = start-1
    for j in range(start, end):
        if listx[j] <= listx[end]:
            i += 1
            listx[i],listx[j]=listx[j],listx[i]
    listx[i+1],listx[end]=listx[end],listx[i+1]
    return i

if __name__ == "__main__":
    list = [95, 103, 52, 285, 29, 58, 208, 0, -1024, 2, 508]
    print(list)
    quickSort(list, 0, len(list)-1)
    print(list)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值