python 实现快速排序(面试经常问到)
Posted xushukui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 实现快速排序(面试经常问到)相关的知识,希望对你有一定的参考价值。
# -*- 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...")
以上是关于python 实现快速排序(面试经常问到)的主要内容,如果未能解决你的问题,请参考以下文章