排序算法之快速排序

#!usr/bin/python
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(1000000) 设置递归深度
# 思路:1.选取第一个数,让它归位,即让它前边的数都比它小,后边的数都比它大
# 2.归位后,分为前后两部分,分别让前后两部分的每一个数进行归位,进行递归即可
def pational(li, left, right):
    temp = li[left]  #待归位元素
    while left < right:
        while left < right and li[right] >= temp: #先从右边最后一个数开始,如果它比待归位元素大,右边指针移动
            right -= 1
        li[left] = li[right]#循环退出条件时要么右边数值比temp小要么就是left==right,此时让右边元素移动到待归位元素处
        print(li,"right")
        while left < right and li[left] <= temp: #运行到此处说明遇到了一个元素比temp小了,此时从右边开始指针移动
            left += 1
        li[right] = li[left]
        print(li,"left")
    li[left] = temp #最终left=right,待归位元素归位
    return left #返回归位的位置


def quick_sort(li, left, right):
    if left < right: #只要left,小于right
        mid = pational(li, left, right)
        print(li,"归位后")
        quick_sort(li, left, mid - 1)
        quick_sort(li, mid + 1, right)


alist = [3, 5, 7, 9, 8, 6, 4, 2, 1]
print(alist)
quick_sort(alist, 0, len(alist) - 1)
print(alist)

# [3, 5, 7, 9, 8, 6, 4, 2, 1]
# [1, 5, 7, 9, 8, 6, 4, 2, 1] right
# [1, 5, 7, 9, 8, 6, 4, 2, 5] left
# [1, 2, 7, 9, 8, 6, 4, 2, 5] right
# [1, 2, 7, 9, 8, 6, 4, 7, 5] left
# [1, 2, 7, 9, 8, 6, 4, 7, 5] right
# [1, 2, 7, 9, 8, 6, 4, 7, 5] left
# [1, 2, 3, 9, 8, 6, 4, 7, 5] 归位后
# [1, 2, 3, 9, 8, 6, 4, 7, 5] right
# [1, 2, 3, 9, 8, 6, 4, 7, 5] left
# [1, 2, 3, 9, 8, 6, 4, 7, 5] 归位后
# [1, 2, 3, 5, 8, 6, 4, 7, 5] right
# [1, 2, 3, 5, 8, 6, 4, 7, 5] left
# [1, 2, 3, 5, 8, 6, 4, 7, 9] 归位后
# [1, 2, 3, 4, 8, 6, 4, 7, 9] right
# [1, 2, 3, 4, 8, 6, 8, 7, 9] left
# [1, 2, 3, 4, 8, 6, 8, 7, 9] right
# [1, 2, 3, 4, 8, 6, 8, 7, 9] left
# [1, 2, 3, 4, 5, 6, 8, 7, 9] 归位后
# [1, 2, 3, 4, 5, 6, 8, 7, 9] right
# [1, 2, 3, 4, 5, 6, 8, 7, 9] left
# [1, 2, 3, 4, 5, 6, 8, 7, 9] 归位后
# [1, 2, 3, 4, 5, 6, 7, 7, 9] right
# [1, 2, 3, 4, 5, 6, 7, 7, 9] left
# [1, 2, 3, 4, 5, 6, 7, 8, 9] 归位后
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值