python 短路法提高二叉堆插入效率
来源:互联网 发布:签名设计图软件 编辑:程序博客网 时间:2024/06/16 09:24
在学习 《problem solving with algorithms and data structure using python》 中的二叉堆时,其插入数据方法是将这个数据放在列表的尾部,然后通过一次次与父节点进行比较,并且交换,实现顺序的改变,原代码如下:
二叉堆插入新数据
def insert(self, newItem): self.heapList.append(newItem) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def percUp(self, index): while index // 2 > 0: if self.heapList[index] < self.heapList[index//2]: tmp = self.heapList[index // 2] self.heapList[index // 2] = self.heapList[index] self.heapList[index] = tmp index = index // 2
percUp 方法,将新元素逐级对比后,向上移动。然而在分析代码过程中发现,当新代码通过数次交换后,不再大于父节点的值,而新的下标取的是父节点。由于插入新数据是在已构建好的数据顺序基础上进行,原有的数据已经是二叉堆,再进一步检查,则不会发生任何交换。
因此,通过设置短路,将检查中断,返回调用处,而不是从底层检查到根节点。实现代码如下:
二叉堆短路插入检查
def insert(self, newItem): self.heapList.append(newItem) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def percUp(self, index): while index // 2 > 0: if self.heapList[index] < self.heapList[index//2]: tmp = self.heapList[index // 2] self.heapList[index // 2] = self.heapList[index] self.heapList[index] = tmp index = index // 2 # if more than parent ,quit else: return
原文见《problem-solving-with-algorithms-and-data-structure-using-python 中文版》
二叉堆的实现
也许仅仅是性能小小的提升,但对于海量数据处理处理而言,仍是比较可观的。
阅读全文
0 0
- python 短路法提高二叉堆插入效率
- 提高数据库插入效率
- SQLite提高插入效率
- 提高数据库插入效率
- 提高数据库插入效率
- 提高mysql的插入效率
- mysql提高数据插入效率
- 提高MySql插入执行效率
- 二叉堆的插入例程
- 二叉堆(插入,删除)
- 二叉堆 删除 插入 调整 堆排序
- 单源最短路---dijkstra模板(二叉堆优化)
- Python笔记:二叉堆及堆排序
- 二叉堆初始化、插入、删去等操作。
- 提高Python运行效率的六个窍门
- 提高Python运行效率的六个窍门
- 提高Python运行效率的六个窍门
- 提高Python运行效率的六个窍门
- 回溯法解决8皇后问题
- python--leetcode104. Maximum Depth of Binary Tree
- 微信开发访问两次服务器
- 使用RUBY遍历目录下的所有文件
- 51nod 1768 Rikka with Sequences KDtree维护历史最大值
- python 短路法提高二叉堆插入效率
- springboot2入门(4-starter-hateoas)
- OpenCV外接USB摄像头
- java知识体系
- Ubuntu扩展硬盘及分区
- CSS3过渡
- Linux中的自动安装脚本
- 使用CSDN-markdown写数学公式
- 【洛谷1463】[SDOI2005]反素数ant