前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【说站】python数据结构堆的介绍

【说站】python数据结构堆的介绍

作者头像
很酷的站长
发布2022-11-23 11:46:04
1650
发布2022-11-23 11:46:04
举报
文章被收录于专栏:站长的编程笔记

python数据结构堆的介绍

说明

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

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

实例

代码语言:javascript
复制
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电脑。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • python数据结构堆的介绍
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档