[硕.Love Python] QuickSort(快速排序)

def partition(a, i, j):
    k = -1
    while True:
        while k * (a[i] - a[j]) >= 0:
            if i == j: 
                return i
            j += k
        a[i], a[j] = a[j], a[i]
        i, j, k = j, i - k, -k

def qsort(a, i, j):
    if i < j:
        k = partition(a, i, j)
        qsort(a, i, k - 1)
        qsort(a, k + 1, j)

def quickSort(a):
    qsort(a, 0, len(a) - 1)

if __name__ == '__main__':
    from random import shuffle

    data = range(100)
    shuffle(data)

    print 'before:\n', data
    quickSort(data)
    print 'after:\n', data
点赞