【说站】python数据结构堆的介绍
2023-06-13 09:13:15 时间
python数据结构堆的介绍
说明
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电脑。
相关文章
- 快速入门Python机器学习(22)
- python 基尼系数_Python计算
- python运行代码不成功_Python | PyCharm无法直接运行(Run)脚本
- Python数据分析之Pandas(五)
- Python语音信号处理
- python hashlib_Python hashlib模块实例使用详解
- python监控网站更新_Python 通过网站search功能监控网站内容更新[通俗易懂]
- python中万物皆对象实现机制(进阶必看)
- 【说站】python顺序搜索的两种形式
- Python数组切片_python print数组
- 什么是Python的标识符_utf-8是什么意思
- Python生成随机数列表_numpy产生指定范围的随机数
- python读取excel文件代码_python怎么加速读取excel
- python使用opencv如何保存图片_OpenCV Python 保存图片
- 人生苦短,我用Python-手把手教你如何使用python写串口调试助手
- 新手学Python可行吗?需要什么基础?(新手学python可行吗?需要什么基础)
- python入门之数据结构详细介绍以及代码示例
- python-Python与PostgreSQL数据库-PostgreSQL数据库的基本知识(一)
- Python 基于python实现的http+json协议接口自动化测试框架源码(实用改进版)详解编程语言
- Python Set intersection() 方法详解编程语言
- win10下 python pymouse无法激活其他窗口的原因详解编程语言
- Python range()快速初始化数字列表
- Python 2.x和Python 3.x,初学者应如何选择?
- Linux 启动 Python编程之旅(linux打开python)
- 安装Python MySQL驱动之快速指南(python安装mysql驱动)
- 如何在你的 Python 游戏中添加一个玩家
- 如何在Linux上将Python脚本设置为后台运行?(linux后台运行python)
- Python操作MySQL数据库的必备模块mysqlpython(mysql_python)