美文网首页
Python 排序算法之堆排序(6/8)

Python 排序算法之堆排序(6/8)

作者: Paycation | 来源:发表于2018-05-13 23:02 被阅读44次

    先放在这里后面再来详解

    概念

    大顶堆(最大堆):要求根节点的关键字既大于或等于左子树的关键字值,又大于或等于右子树的关键字值。
    最小堆则正好相反。

    def heap_sort(lst):
        def sift_down(start, end):
            """最大堆调整"""
            root = start
            while True:
                child = 2 * root + 1
                if child > end:
                    break
                if child + 1 <= end and lst[child] < lst[child + 1]: # right child 大
                    child += 1 # child 的含义变为 right child 的位置
                if lst[root] < lst[child]: # root 小于任意一个 child
                    lst[root], lst[child] = lst[child], lst[root] # swap
                    root = child # 
                else:
                    break
    
        # 创建最大堆
        for start in range((len(lst) - 2) // 2, -1, -1):
            sift_down(start, len(lst) - 1)
    
        # 堆排序
        for end in range(len(lst) - 1, 0, -1):
            lst[0], lst[end] = lst[end], lst[0]
            sift_down(0, end - 1)
        return lst
    

    相关文章

      网友评论

          本文标题:Python 排序算法之堆排序(6/8)

          本文链接:https://www.haomeiwen.com/subject/mqkrdftx.html