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\r\n" % lst)
    return lst


l = [3, 6, 9, 1, 8, 7, 2, 5, 4, 0]
print("排序前: %s\r\n" %l)
print("\r\n排序后:  %s" % selectSort2(l))

list以二叉树型式表现:

输出结果:

E:\python\algorithm>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]

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

posted @ 2018-01-30 16:33  sam11  阅读(142)  评论(0编辑  收藏  举报