python实现快排

快速排序 PYTHON

  1. 不那么好看的快排,参考 博客
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        base = arr[0]
        less = [v for v in arr[1:] if v<=base]
        more = [v for v in arr[1:] if v>base]
        return quick_sort(less) + [base] + quick_sort(more)
  1. 好看一点的快排,参考 博客
def quick_sort(arr,l,r):
    if l < r:
        q = partition(arr,l,r)
        quick_sort(arr,l,q-1)
        quick_sort(arr,q+1,r)

def partion(arr,l,r):
    x = arr[r]
    i = l - 1
    for j in (l,r):
        if arr[j] <= x:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i+1], arr[r] = arr[r], arr[i+1]
    return i+1
posted @ 2019-07-14 16:57  静_渊  阅读(3153)  评论(0编辑  收藏  举报