Just for a Record of Knowledge
快速排序使用分治法(divide and conquer)策略来把一个序列(list)分为较小和较大的2个子序列,然后递归地排序两个子序列。
步骤为:
选取基准值有数种具体方法,此选取方法对排序的时间性能有决定性影响。
# arr[] --> 排序数组
# low --> 起始索引
# high --> 结束索引
def partition(arr,low,high):
i = low-1
pivot = arr[high]
for j in range(low , high):
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return i+1
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)