python双指针快速排序

原地排序,常数空间复杂度,平均时间复杂度O(logN),最差时间复杂度O(N2)

def QuickSort(data, start, end):
    if start<end:
        i, j = start, end
        anchor = data[i]
        while i != j :
            while data[j]>=anchor and j>i:
                j -= 1
            # when data[j]
            if j>i:
                data[i] = data[j]
                i += 1
            while data[i]<=anchor and i<j:
                i += 1
            if i<j:
                data[j] = data[i]
                j -= 1
        data[i] = anchor
        QuickSort(data, start, i-1)
        QuickSort(data, i+1, end)
    
import random
data = [random.randint(-10, 10) for _ in range(10)]
QuickSort(data, 0, len(data)-1)
print(data)

你可能感兴趣的:(python)