Python实现快排

# -*- coding: UTF-8 -*-
def partitoin(l, p, q):
    pivot = l[p]
    while p < q:
        while p < q and l[q] >= pivot:
            q -= 1
        l[p] = l[q]
        while p < q and l[p] <= pivot:
            p += 1
        l[q] = l[p]
    l[p] = pivot
    return p

def quicksort(l, low, high): #method 1
    if low < high:
        mid = partitoin(l, low, high)
        quicksort(l, low, mid - 1)
        quicksort(l, mid + 1, high)
    return l


def qsort(seq): #method 2
    if seq == []:
        return []
    else:
        pivot = seq[0]
        lesser = qsort([x for x in seq[1:] if x < pivot])
        greater = qsort([x for x in seq[1:] if x >= pivot])
        return lesser + [pivot] + greater


if __name__ == "__main__":
    ls = [5, 8, 1, 2, 3, 8, 9, 10, -1, -45]
    print 'result is '
    seq = [5, 6, 78, 9, 0, -1, 2, 3, -65, 12]
    print(qsort(seq))
    print quicksort(seq, 0, len(seq) - 1)

你可能感兴趣的:(随笔)