python数据结构堆的介绍

2025-12-01 0 1,961

说明

1、堆是用数据结构来实现的一种算法:树,数组均可。堆本身是一棵完全二叉树。

2、特点,堆:所有父节点的值大于子节点的值。最小堆,所有父节点的值小于子节点的值。

实例

class Heap(object):
    def __init__(self, list=[]):
        self.root = None
        self.list = list
        self.tree = None
        self.len = len(list)
 
    # 建堆
    def bulid_heap(self):
        if self.list != []:
            final_parent_node = int((self.len - 1) / 2)
            while final_parent_node >= 0:
                self.heapfy(final_parent_node, self.len)
                final_parent_node -= 1
 
    # 对当前节点以及向下所有子节点的一次节点交换
    def heapfy(self, node, len):
        node_left = 2 * node + 1
        node_right = 2 * node + 2
        max = node
        if node_left < len and self.list[node_left] > self.list[max]:
            max = node_left
        if node_right < len and self.list[node_right] > self.list[max]:
            max = node_right
        if max != node:
            self.swap(max, node)
            self.heapfy(max, len)
 
    # 交换元素方法
    def swap(self, i, j):
        self.list[j], self.list[i] = self.list[i], self.list[j]
 
    # 堆排序
    def heap_sort(self):
        len = self.len - 1
        while len >= 0:
            self.swap(0, len)
            self.heapfy(0, len)
            len -= 1
 
 
if __name__ == "__main__":
    list = [5, 7, 3, 1, 10, 0]
    heap = Heap(list)
    print("初始列表:{}".format(heap.list))
    heap.bulid_heap()
    print("堆化:{}".format(heap.list))
    heap.heap_sort()
    print("排序:{}".format(heap.list))

以上就是python数据结构堆的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python数据结构堆的介绍 https://www.zhiup.top/1336.html

相关