码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现快速排序(面试经常问到)

时间:2019-10-21 16:18:18      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:sort   ext   python   快速排序   turn   while   xtend   quick   tar   

# -*- 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 实现快速排序(面试经常问到)

标签:sort   ext   python   快速排序   turn   while   xtend   quick   tar   

原文地址:https://www.cnblogs.com/nyist-xsk/p/11713907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!