zoukankan      html  css  js  c++  java
  • Python选择排序(2)

    Python代码:

    """
    选择排序(2)锦标赛排序、二叉树排序
    
    小堆顶:根节点值最小,父节点值不大于左右子节点
    
    如果将list视为二叉树,则:
    根节点是list[0]
    父节点是list[i],则左子节点是list[i*2+1],右子节点是list[i*2+2]
    
    例如list=[3, 6, 9, 1, 8, 7, 2, 5, 4, 0],则:
    根节点是list[0]:3
    父节点有很多:
    --父节点lsit[0]:3的左右子节点list[1]:6,list[2]:9
    --父节点lsit[1]:6的左右子节点list[3]:1,list[4]:8
    --父节点lsit[2]:9的左右子节点list[5]:7,list[6]:2
    
    
    """
    
    def selectSort2(lst):
        arr = []
        while len(lst) > 2:
            lst = btm(lst)
            arr.insert(len(arr), lst[0])
            lst.pop(0)
        return arr + lst
    
    # 小堆顶(不仅仅是小堆顶,每1个根和其左右子节点,3个数都是按照从小到大顺序排列的)
    def btm(lst):
        print("遍历前<=:%s" % lst)
        for root in range(len(lst)-1,-1,-1):
            left = root*2+1
            right = root*2+2
            if right < len(lst):
                if lst[left] > lst[right]:
                    lst[left],lst[right] = lst[right],lst[left]
                if lst[root] > lst[right]:
                    lst[root],lst[right] = lst[right],lst[root]
            if left < len(lst):
                if lst[root] > lst[left]:
                    lst[root],lst[left] = lst[left],lst[root]
        print("遍历后=>:%s
    " % lst)
        return lst
    
    
    l = [3, 6, 9, 1, 8, 7, 2, 5, 4, 0]
    print("排序前: %s
    " %l)
    print("
    排序后:  %s" % selectSort2(l))

    list以二叉树型式表现:

    输出结果:

    E:pythonalgorithm>python3 selectSort2.py
    排序前: [3, 6, 9, 1, 8, 7, 2, 5, 4, 0]
    
    遍历前<=:[3, 6, 9, 1, 8, 7, 2, 5, 4, 0]
    遍历后=>:[0, 2, 3, 1, 6, 7, 9, 4, 5, 8]
    
    遍历前<=:[2, 3, 1, 6, 7, 9, 4, 5, 8]
    遍历后=>:[1, 2, 3, 5, 7, 4, 9, 6, 8]
    
    遍历前<=:[2, 3, 5, 7, 4, 9, 6, 8]
    遍历后=>:[2, 3, 5, 4, 7, 6, 9, 8]
    
    遍历前<=:[3, 5, 4, 7, 6, 9, 8]
    遍历后=>:[3, 4, 5, 6, 7, 8, 9]
    
    遍历前<=:[4, 5, 6, 7, 8, 9]
    遍历后=>:[4, 5, 6, 7, 8, 9]
    
    遍历前<=:[5, 6, 7, 8, 9]
    遍历后=>:[5, 6, 7, 8, 9]
    
    遍历前<=:[6, 7, 8, 9]
    遍历后=>:[6, 7, 8, 9]
    
    遍历前<=:[7, 8, 9]
    遍历后=>:[7, 8, 9]
    
    
    排序后:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    =====结束=====

  • 相关阅读:
    Linux下的 .o、.a、.so文件
    第三章、主机规划与磁盘分区
    debian linux中文桌面系统安装
    C++开源库,欢迎补充。
    C#获取电脑硬件信息(CPU ID、主板ID、硬盘ID、BIOS编号)
    C# CPU,硬盘,mac地址灯本地信息查询
    打造属于自己的支持版本迭代的Asp.Net Web Api Route
    PreApplicationStartMethodAttribute的使用
    Web Api in Orchard
    Dependency Injection in ASP.NET Web API 2 Using Unity
  • 原文地址:https://www.cnblogs.com/sam11/p/8385713.html
Copyright © 2011-2022 走看看