递归实现:
def quicksort(arr, start, end):
if start >= end:
return
pivot = arr[start]
low, high = start, end
while low < high:
while arr[high] >= pivot and low < high:
high -= 1
arr[low] = arr[high]
while arr[low] <= pivot and low < high:
low += 1
arr[high] = arr[low]
arr[low] = pivot
quicksort(arr, start, low-1)
quicksort(arr, low+1, end)
return
arr = [12, 11, 13, 5, 6, 7, 88]
if arr != []:
quicksort(arr, 0, len(arr) - 1)
print(arr)
优雅一点的写法:但有空间复杂度了
def quicksort(arr):
if arr == [] or len(arr) == 1:
return arr
pivot = arr[0]
L = [ele for ele in arr[1:] if ele < pivot]
R = [ele for ele in arr[1:] if ele >= pivot]
return quicksort(L) + [pivot] + quicksort(R)
arr = [12, 11, 13, 5, 6, 7, 88]
arr_sort = quicksort(arr)
print(arr_sort)