问题
1945年,现代计算机之父冯·诺伊曼提出归并排序.
归并排序算法:无论最好还是最坏时间复杂度均为:O(nlgn); 空间复杂度为 O(n); 是一种稳定的排序算法.
方法一:使用递归(分而治之)
def merge_sort(arr):
if len(arr) == 1:# 首先是递归.需要找出终止条件
return arr
middle = len(arr)//2 # 向下取整.
left = arr[:middle]
right = arr[middle:]
return merge(merge_sort(left),merge_sort(right))
def merge(left,right):
result = []
while len(left)>0 and len(right)>0:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
result += left
result += right
return result
print(merge_sort([79,84,21,6]))
print(merge_sort([11, 99, 33 , 69, 77, 88, 55, 11, 33, 36,39, 66, 44, 22]))
画一遍图就会对这个算法明晰了.
分解为子问题 : merge_sort([79,84,21,6]) = > merge_sort([79,84]) merge_sort([21,6]) => merge_sort([79]) merge_sort([84]) merge_sort([21]) merge_sort([6])
子问题得出最优解并合并为主问题的最优解: merge_sort([79]) merge_sort([84]) merge_sort([21]) merge_sort([6]) => merge_sort([79,84]) merge_sort([6,21]) => return [6,21,79,84]
方法二:使用循环
待学习~