快速排序采用分而治之的策略,以及递归的思想
快速排序步骤如下:
1.选择基准值
2.将数组分成两个子数组,小于基准值的元素和大于基准值的元素
3.对这两个子数组进行快速排序
def quicksort(array):
if len(array) < 2:#基线条件
# base case, arrays with 0 or 1 element are already "sorted"
return array
else:
# recursive case
pivot = array[0]#选择基准值
# sub-array of all the elements less than the pivot
less = [i for i in array[1:] if i <= pivot]
# sub-array of all the elements greater than the pivot
greater = [i for i in array[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
print(quicksort([10, 5, 2, 3]))