归并排序和快排速度怎么差距这么大,同样都是递归实现
上面是归并,下面是快排,随机1000000个数字排序
代码
def merger(left, right): if not left: return right if not right: return left res=[] while left and right: if left[0] < right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) if left: res+=left else: res += right return res def merger_sort(arr): if len(arr)<=1: return arr mid=len(arr)//2 left = merger_sort(arr[:mid]) right = merger_sort(arr[mid:]) return merger(left,right) def quick_sort(arr): if len(arr)<=1: return arr t=arr[0] return quick_sort([x for x in arr[1:] if x <=t])+[t] +quick_sort([x for x in arr[1:] if x >t])