思路:归并排序采用经典的分治策略,将问题分成一些小的问题然后递归求解,而治的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之。
一图解百惑,上图!
![](https://i-blog.csdnimg.cn/blog_migrate/642f9a81180ba1bb477d470ed539ce5f.gif)
话不多说,上代码!
def merge_sort(collection: list) -> list:
# 归并排序:分解-解决-合并三步曲!
l = collection # 简化参数名
def merge(left: list, right: list) -> list:
def _merge():
while left and right:
yield (left if left[0] < right[0] else right).pop(0)
yield from left
yield from right
return list(_merge())
if len(l) <= 1:
return l
mid = len(l) // 2 # 长度除2取整
return merge(merge_sort(l[:mid]), merge_sort(l[mid:])) # 递归
if __name__ == '__main__':
test = [4,3,2,1]
print(merge_sort(test))
总结
分解-解决-合并三步曲!