Python实现快速排序

# 使用递归快速排序算法排序一个数组或列表
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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值