# -*- coding: UTF-8 -*-
# 递归实现, 把过程打印出来便于理解
def quick_sort1(lis, start, end):
if start >= end:
return
lf = start
rg = end
base = lis[lf]
while lf < rg:
while lf < rg and lis[rg] <= base:
rg -= 1
lis[lf] = lis[rg]
print("while1", lis)
while lf < rg and lis[lf] > base:
lf += 1
lis[rg] = lis[lf]
print("while2", lis)
lis[lf] = base
print(lis)
quick_sort1(lis, rg+1, end)
quick_sort1(lis, start, lf - 1)
def quick_sort2(array, l, r):
if l < r:
q = partition(array, l, r)
quick_sort2(array, l, q - 1)
quick_sort2(array, q + 1, r)
def partition(array, l, r):
x = array[r]
i = l - 1
for j in range(l, r):
if array[j] <= x:
i += 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[r] = array[r], array[i + 1]
return i + 1
# 迭代替代递归,使用栈实现
def quick_sort3(array, l, r):
if l >= r:
return
stack = []
stack.append(l)
stack.append(r)
while stack:
low = stack.pop(0)
high = stack.pop(0)
if high - low <= 0:
continue
x = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= x:
i += 1
array[i], array[j] = array[j], array[i]
array[i + 1], array[high] = array[high], array[i + 1]
stack.extend([low, i, i + 2, high])
if __name__ == "__main__":
# lis1 = [6, 4, 3, 5, 2, 1, 7, 8, 9]
lis = [6, 3, 5, 2, 1, 7, 8, 9, 4]
print("start....")
quick_sort3(lis, 0, len(lis)-1)
print(lis)
print("end...")
原文地址:https://www.cnblogs.com/nyist-xsk/p/11713907.html
时间: 2024-10-23 07:49:20