用Python实现八大排序算法--归并排序

一、归并排序概述

1.归并排序

将待排序序列R[0…n-1]看成是n个长度为1的有序序列,将相邻的有序表成对归并,得到n/2个长度为2的有序表;将这些有序序列再次归并,得到n/4个长度为4的有序序列;如此反复进行下去,最后得到一个长度为n的有序序列。
综上可知:
归并排序其实要做两件事:
(1)“分解”——将序列每次折半划分。
(2)“合并”——将划分后的序列段两两合并后排序。

2.算法特性分析

时间复杂度:O(nlogn)
空间复杂度:O(n)
稳定性: 稳定

3.归并排序示意图

《用Python实现八大排序算法--归并排序》

二、Python实现

#归并排序
def MergeSort(lists):
    if len(lists) <= 1:
        return lists
    mid = len(lists)//2
    #递归
    listA = MergeSort(lists[:mid])
    listB = MergeSort(lists[mid:])
    print("========listA========")
    print(listA)
    print("========listB========")
    print(listB)
    return MergeSortedLists(listA, listB)

#合并两个有序数集
def MergeSortedLists(listA, listB):
    newList = list()
    a = 0
    b = 0
    # Merge the two lists together until one is empty
    while a < len(listA) and b < len(listB):
        if listA[a] < listB[b]:
            newList.append(listA[a])
            a += 1
        else:
            newList.append(listB[b])
            b += 1
    # If listA contains more items,append them to newList
    while a < len(listA):
        newList.append(listA[a])
        a += 1

    while b < len(listB):
        newList.append(listB[b])
        b += 1
    return newList

    # If listB contains more items,append them to newList

if __name__ == "__main__":
    lists = [3, 5, 4, 2, 1, 6]
    print(lists)
    result = MergeSort(lists)
    print(result)

运行结果如下所示:

《用Python实现八大排序算法--归并排序》

程序运行结果解释:

       [3,5,4,2,1,6]
            ||
     [3,5,4] + [2,1,6]
        ||        ||
   [3] + [5,4] [2] + [1,6]
          ||          ||
       [5]+[4]     [1]+[6]
    原文作者:排序算法
    原文地址: https://blog.csdn.net/chibangyuxun/article/details/53012537
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞