[笔记]binaryheap
2015-08-07 20:47
399 查看
Binary Heap 二叉堆
优先队列在图算法中有着广泛应用。如何构建优先队列呢?
使用列表?
在列表中,插入操作为O(n),排序操作为O(nlogn)。
但是,我们可以做的更好。
这种数据结构是二叉堆。
由二叉堆构建的优先队列的出队入队操作为O(lgn)
二叉堆分为最小堆,最大堆。
最小堆为在堆顶放置最小元素的堆结构。最顶端就是最小值。
binary heap operations 二叉堆的操作
(1) BinaryHeap() 构建实例(2) insert(k) 插入k
(3) findmin() 找到最小值
(4) delmin() 删除最小值
(5) isEmpty() 是否为空
(6) size() 元素个数
(7) buildHeap(list) 为列表构建堆
Binary heap implement 二叉堆的实现
堆是利用索引值之间的关系表示节点的父子关系的。比如,一列数组中,索引值为p 的元素中存放一个节点。
那么,索引值为2p 和 2p+1 的位置上分别存放左子节点,右子节点。
The Heap Order Property 堆中元素顺序的特性
作为最小堆,对于索引为x上的节点,其父节点的索引为p ,则p中的元素小于等于x中的元素。heap operation 堆中操作
class BinHeap(object): def __init__(self): self.curSize = 0 self.heapList = [0] def percUp(self,i): # the index cut down by 2 to find the parent index while i >=2: upper = i//2 if self.heapList[upper] > self.heapList[i]: self.heapList[upper], self.heapList[i] = self.heapList[i], self.heapList[upper] i = upper def insert(self, k): # insert the new one at the bottom the pull it up self.heapList.append(k) self.curSize += 1 self.percUp(self.curSize) def minChildIdx(self, father): # find the min child index watch out the index out of range if father * 2 + 1 > self.curSize: return father*2 else: if self.heapList[father*2] < self.heapList[father*2+1]: return father*2 else: return father*2+1 def percDown(self,i): # from top to bottom exchange the parent with the min child while (i * 2) <= self.curSize: mc = self.minChildIdx(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def delMin(self): # exchange the bottom and the top, the percDown the new top to downside minVal = self.heapList[1] self.heapList[1] = self.heapList[self.curSize] self.curSize -= 1 self.heapList.pop() self.percDown(1) return minVal def buildHeap(self, aList): # percDown from bottom to top self.curSize = len(aList) idx = len(aList) // 2 aList.insert(0,0) self.heapList = aList while idx > 0: self.percDown(idx) idx -= 1 bh = BinHeap() bh.insert(5) bh.insert(7) bh.insert(3) bh.insert(11) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) bh.buildHeap([2,3,6,1,0,9,7,4,3]) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) print(bh.delMin()) 3 5 7 11 0 1 2 3
相关文章推荐
- Java线程:线程的同步与锁
- HDOJ 1253 胜利大逃亡 (三维BFS+技巧)
- 蓝牙技术转载源码
- pat 1085. Perfect Sequence (25)
- virtools3.0-3.5 下载地址
- (转)Java线程:线程的同步与锁
- uva 11040 - Add bricks in the wall
- 线程栈模型与线程的变量、线程状态转换
- java Socket多线程聊天程序(适合初学者)
- (转)线程栈模型与线程的变量、线程状态转换
- 如何删除 CentOS 6 更新后产生的多余的内核?
- 扒照片
- struts基本开发流程
- poj 2406 Power Strings (kmp)
- Why Docker is Not Yet Succeeding Widely in Production
- BZOJ2911 : [Poi1997]The Number of Symmetrical Choices
- log4net按日志级别(debug,info,warn,error,fatal)生成日志目录,同时每小时生成一个日志文件
- 12、C语言和设计模式(代理模式)
- BZOJ 2049 [Sdoi2008]Cave 洞穴勘测 LCT
- 11gR2更换OCR和VOTE