1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| def quick_sort(arr): # 交换元素位置 def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i]
# 分区,左小右大 def partition(array, left, right): storeIndex = left # 基准,直接选择最右侧的 pivot = arr[right]
for i in range(left, right): if arr[i] < pivot: swap(arr, storeIndex, i) storeIndex += 1
swap(arr, right, storeIndex) # 将基准元素与storeIndex做交换
return storeIndex
def sort(arr, left, right): if left > right: return
storeIndex = partition(arr, left, right) sort(arr, left, storeIndex - 1) sort(arr, storeIndex + 1, right)
sort(arr, 0, len(arr) - 1)
return arr
if __name__ == '__main__': arr = [10, 8, 4, 7, 5] sort_arr = quick_sort(arr) print(sort_arr)
|