# encoding=utf-8 def merge_sort(alist): """归并排序""" n = len(alist) if n == 1: return alist mid = n // 2 # 对分割的左半部分进行归并排序 left_sorted_li = merge_sort(alist[:mid]) # 对分割的右半部分进行归并排序 right_sorted_li = merge_sort(alist[mid:]) # 对排序之后的两部分进行合并 # 定义两个游标 left, right = 0, 0 merge_result_li = [] left_n = len(left_sorted_li) right_n = len(right_sorted_li) while left < left_n and right < right_n: if left_sorted_li[left] <= right_sorted_li[right]: merge_result_li.append(left_sorted_li[left]) left += 1 else: merge_result_li.append(right_sorted_li[right]) right += 1 merge_result_li += left_sorted_li[left:] merge_result_li += right_sorted_li[right:] # 将合并后的结果 一个新的类别返回 return merge_result_li if __name__ == '__main__': alist = [22, 1, 4, 553, 3, 212, 77] print("before alist: %s" % alist) sorted_alist = merge_sort(alist) print("after alist: %s" % alist) print("sorted new list %s" % sorted_alist)