-
分解合并
def merge(li,low,mid,high):
i = low # 右边箭头
j = mid + 1 # 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]) # li[i] > li[j],谁小谁被添加到列表中
j += 1
# 当while执行完,肯定有把一边没数了
while i <= mid:
ltmp.append(li[i])
i += 1
while j <= high:
ltmp.append(li[j])
j += 1
li[low:high+1] = ltmp
# 测试
# li = [2,4,5,7,1,3,6,8]
# merge(li,0,3,7)
# print(li)
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)
# 测试
# li = [1,4,2,5,3,6,9,8,7]
# merge_sort(li,0,len(li)-1)
# print(li)
-
时间复杂度:O(nlogn)
-
空间复杂度:O(n)