算法--归并排序
博客:https://www.cnblogs.com/chengxiao/p/6194356.html
https://www.cnblogs.com/piperck/p/6030122.html
python实现:
def merge(left, right): """ params: left=[1,2,4] right=[3,6,7] h=j=0: 初始化索引 循环结束后,判断:如果左边的循环完了, 把右边剩下的循环插入结果集c (j=3 len=3; h=1 len=3)或者else。。。。 """ c = [] h = j = 0 while j < len(left) and h < len(right): if left[j] < right[h]: c.append(left[j]) j += 1 else: c.append(right[h]) h += 1 if j == len(left): for i in right[h:]: c.append(i) else: for i in left[j:]: c.append(i) return c def merge_sort(li): """ step1: 如果len=1,不用排序了,或者说已经排好了 step2: 递归拆分 step3: 合并 """ if len(li) <= 1: return li middle = len(li) // 2 left = merge_sort(li[:middle]) right = merge_sort(li[middle:]) return merge(left, right) if __name__ == ‘__main__‘: a = [4, 7, 8, 3, 5, 9] print(merge_sort(a))