当然不是最好的方法,加上这个著名的算法将有几十个完美的实现..这是我的,很容易理解
def sub_partition(array, start, end, idx_pivot):
'returns the position where the pivot winds up'
if not (start <= idx_pivot <= end):
raise ValueError('idx pivot must be between start and end')
array[start], array[idx_pivot] = array[idx_pivot], array[start]
pivot = array[start]
i = start + 1
j = start + 1
while j <= end:
if array[j] <= pivot:
array[j], array[i] = array[i], array[j]
i += 1
j += 1
array[start], array[i - 1] = array[i - 1], array[start]
return i - 1
def quicksort(array, start=0, end=None):
if end is None:
end = len(array) - 1
if end - start < 1:
return
idx_pivot = random.randint(start, end)
i = sub_partition(array, start, end, idx_pivot)
#print array, i, idx_pivot
quicksort(array, start, i - 1)
quicksort(array, i + 1, end)
好的,首先是分区子例程的单独函数。它需要数组,
兴趣点的起点和终点,以及枢轴索引。这个功能应该很清楚
然后快速排序对整个数组第一次调用分区子例程;然后
递归地调用自身来对枢轴之前的所有内容以及之后的所有内容进行排序。
如果你不明白什么就问