def merge_sort(alist):
'''归并排序'''
n = len(alist)
if n <= 1:
return alist
mid = n//2
left_list = merge_sort(alist[:mid])
right_list = merge_sort(alist[mid:])
#2个有序的合并
left_point = 0
right_point = 0
result = []
while left_point < len(left_list) and right_point < len(right_list):
if left_list[left_point] < right_list[right_point]:
result.append(left_list[left_point])
left_point += 1
else:
result.append(right_list[right_point])
right_point += 1
result += left_list[left_point:]
result += right_list[right_point:]
return result
if __name__ == '__main__':
li = [1, 3, 9, 0, -30, -54, 86]
print(li)
sorted_list = merge_sort(li)
print('original list:',li)
print('new list:',sorted_list)
C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
[1, 3, 9, 0, -30, -54, 86]
original list: [1, 3, 9, 0, -30, -54, 86]
new list: [-54, -30, 0, 1, 3, 9, 86]
Process finished with exit code 0