#!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]