#!/usr/bin/env python
# -*- coding:utf8 -*-
def merge_sort(li):
n = len(li)
if n <= 1:
return
# 1 递归分解,直到不能分为止
left = li[0: n // 2]
right = li[n//2:n]
merge_sort(left)
merge_sort(right)
# 2 返回合并,合并步骤1分解出来的两个序列(这两个序列是有序的)
# 因为我们已经对left和right调用了merge_sort这样的排序函数,所以,left和right已经有序
# 1)清空原序列li
li[:] = []
# 2)left和right合并到li上
l_index = 0
r_index = 0
while l_index < len(left) and r_index < len(right):
if left[l_index] <= right[r_index]:
li.append(left[l_index])
l_index += 1
else:
li.append(right[r_index])
r_index += 1
# 至此,左右序列其中之一遍历结束
li += left[l_index:]
li += right[r_index:]
if __name__ == '__main__':
li = [5,6,9,3,2,5,8,2,1,4,5,7,6,9]
merge_sort(li)
print(li)
python 归并排序
最新推荐文章于 2024-07-19 17:03:11 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)