# 使用递归快速排序算法排序一个数组或列表
def quickSort( theSeq ):
n = len( theSeq )
recQuickSort( theSeq, 0, n-1 )
# 使用虚拟片段递归实现
def recQuickSort( theSeq, first, last ):
# 检查基本情况
if first >= last :
return
else :
# 保存主元pivot
pivot = theSeq[first]
#划分序列并获取主元位置
pos = partitionSeq( theSeq, first, last )
# 在两个子序列上重复处理过程
recQuickSort( theSeq, first, pos - 1 )
recQuickSort( theSeq, pos + 1, last )
# 使用first键做主元划分子序列
def partitionSeq( theSeq, first, last ):
# 保存主元值的副本
pivot = theSeq[first]
# 查找主元位置并移动主元附近元素
left = first + 1
right = last
while left <= right :
# 找到第一个大于主元的键first key
while left < right and theSeq[left] < pivot :
left += 1
# 查找序列中小于主元的最后的键Find the last key
while right >= left and theSeq[right] >= pivot :
right -= 1
# 如果没能完成这次划分则交换两个键
if left < right :
tmp = theSeq[left]
theSeq[left] = theSeq[right]
theSeq[right] = tmp
# 把主元放到适当位置
if right != first :
theSeq[first] = theSeq[right]
theSeq[right] = pivot
# 返回主元值得索引位置
return right
Python实现快速排序
最新推荐文章于 2018-10-14 22:28:54 发布