归并排序
def merge_sort(li, low, high):
if low < high: # 至少有两个元素
mid = (low + high) //2
merge_sort(li, low, mid) # 吧左边弄成有序
merge_sort(li, mid+1, high) #把右边弄成有序
merge(li,low, mid, high)
是不是感觉很像之前的快速排序,把归并排序看成三部,先归并排序左边,再归并排序右边,最后整合起来。
def merge(li, low, mid, high):
i = low
j = mid+1
ltmp = []
while i <= mid and j <= high:
if li[i] < li[j]:
ltmp.append(li[i])
i+=1
else:
ltmp.append(li[j])
j += 1
while u <= mid:
ltmp.append(li[i])
i += 1
while j <= highL
ltmp.append(li[j])
j +=1
li[low:high+1] = ltmp
# 空间复杂度n 时间复杂度 nlogn