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]

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

  • 相关阅读:
    可变参数函数总结
    小例子一步一步解释“函数调用过程中栈的变化过程”
    自己动手实现C标准库中sqrt()函数
    无符号整数翻转函数实现reverse_bits(unsigned int value)
    stdarg.h源代码
    判断两个字符串s1 s2所含字符是否相同
    亚马逊20120915网上机试第一题:atoi函数
    [wp7软件]wp7~~HTC官方软件~~集合贴~~
    [wp7软件]wp7~~相册加密软件~~集合贴~~
    [wp7软件]wp7~~密码管理软件~~集合贴~~
  • 原文地址:https://www.cnblogs.com/sam11/p/8385713.html
Copyright © 2011-2022 走看看