1. 排序
快速排序(quick sort)
- 形式一:借助 partition 辅助函数
def partition(seq): pivot, seq = seq[0], seq[1:] low = [x for x in seq if x <= pivot] high = [x for x in seq if x not in low] return low, pivot, high def qsort(seq): if len(seq) <= 1: return seq low, pivot, high = partition(seq) return qsort(low)+[pivot]+qsort(high)
- 形式二:直接返回数组
def qsort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr)//2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return qsort(left) + middle + qsort(right)