Python 归并排序
不断的分成2组,递归后,合并2个分组
稳定排序,时间复杂度都是 O(nlogn) O ( n l o g n ) ,空间复杂度 O(n) O ( n )
def merge_sort(L):
if len(L)<2:
return L
mid = len(L)//2
left = merge_sort(L[:mid])
right = merge_sort(L[mid:])
return merge(left, right)
def merge(left, right):
l=r=0
res = []
while l<len(left) and r<len(right):
if left[l]<=right[r]:
# =保证排序稳定
res.append(left[l])
l += 1
else:
res.append(right[r])
r += 1
if l < len(left):
res += left[l:]
if r < len(right):
res += right[r:]
return res