• 技术文章 >Python技术 >Python基础教程

    python归并排序如何理解

    小妮浅浅小妮浅浅2021-08-19 16:51:24原创2213

    说明

    1、归并排序是一种高效、稳定的合并运算排序算法,它是采用分治方法的典型应用。

    2、基本思想大致为:首先通过递归的方式将给定的数组二分为二分,再按大小比较进行两次大小比较排序,最后逐级合并完成总体的排序。

    归并排序更有效,它设置了n个列长,将数列分成小数列,需要logn步骤,每个步骤都是一个合并有序数列的过程,时间复杂性为O(nlogn),即O(n)。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    import random

      

    def ConfiationAlgorithm(str):

        if len(str) <= 1: #子序列

            return str

        mid = (len(str) / 2)

        left = ConfiationAlgorithm(str[:mid])#递归的切片操作

        right = ConfiationAlgorithm(str[mid:len(str)])

        result = []

        #i,j = 0,0

      

        while len(left) > 0 and len(right) > 0:

            if (left[0] <= right[0]):

                #result.append(left[0])

                result.append(left.pop(0))

                #i+= 1

            else:

                #result.append(right[0])

                result.append(right.pop(0))

                #j+= 1

      

        if (len(left) > 0):

            result.extend(ConfiationAlgorithm(left))

        else:

            result.extend(ConfiationAlgorithm(right))

        return result  

    if __name__ == '__main__':

        a = [20,30,64,16,8,0,99,24,75,100,69]

        print ConfiationAlgorithm(a)

        b = [random.randint(1,1000) for i in range(10)]

        print ConfiationAlgorithm(b)

    以上就是python归并排序的理解,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python归并排序
    上一篇:python元组如何打包和解包 下一篇:python非绑定方法是什么

    相关文章推荐

    • 什么是网络协议• python中的去除重复项的操作• python中少见的函数map()和partial()• python的sort()排序方法• Python中的文件读写-理论知识

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网