python算法-0排序-5.快速排序

python算法-0排序-5.快速排序

 

python算法-0排序-5.快速排序

 

在线运行:https://pyleetcode.gitee.io/codes_html/SYL_0%E6%8E%92%E5%BA%8F_5%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F.html

 

def Partion(arr, left, right):
    # 一次对比操作,返回中间索引(索引前面比他小,后面比他大)
    tag = right # 作为判断点,一轮后,比他小的会到他前面,比他大的在他后面
    center = arr[tag]
    while left < right:
        while left < right and arr[left] <= center:
            left += 1
        while left < right and arr[right] >= center:
            right -= 1
        arr[left], arr[right] = arr[right], arr[left]
    arr[left], arr[tag] = arr[tag], arr[left]
    return left


def quickSort(arr):
    left = 0
    right = len(arr) - 1
    # 多伦操作的索引记录数组,这样做避免递归写法
    stack = []
    # 初始时,对最左、右的进行一轮Partion
    stack.append([left, right])
    while len(stack) != 0:
        pos = stack.pop()
        center_i = Partion(arr, pos[0], pos[1])
        if center_i - 1 > pos[0]:
            stack.append([pos[0], center_i - 1])
        if center_i + 1 < pos[1]:
            stack.append([center_i + 1, pos[1]])


if __name__ == '__main__':
    data = [16, 25, 39, 27, 12, 8, 45, 63]
    quickSort(data)
    print(data)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值