[笔记]binaryheap
来源:互联网 发布:笔记本温度测试软件 编辑:程序博客网 时间:2024/06/05 02:39
Binary Heap 二叉堆
优先队列在图算法中有着广泛应用。
如何构建优先队列呢?
使用列表?
在列表中,插入操作为
但是,我们可以做的更好。
这种数据结构是二叉堆。
由二叉堆构建的优先队列的出队入队操作为
二叉堆分为最小堆,最大堆。
最小堆为在堆顶放置最小元素的堆结构。最顶端就是最小值。
binary heap operations 二叉堆的操作
(1) BinaryHeap() 构建实例
(2) insert(k) 插入k
(3) findmin() 找到最小值
(4) delmin() 删除最小值
(5) isEmpty() 是否为空
(6) size() 元素个数
(7) buildHeap(list) 为列表构建堆
Binary heap implement 二叉堆的实现
堆是利用索引值之间的关系表示节点的父子关系的。
比如,一列数组中,索引值为
那么,索引值为
The Heap Order Property 堆中元素顺序的特性
作为最小堆,对于索引为
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 -= 1bh = 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())357110123
0 0
- [笔记]binaryheap
- BinaryHeap
- phonebook(binaryheap)
- PriorityQueue的BinaryHeap实现
- BinaryHeap 的C++实现
- BinaryHeap二叉堆
- 数据结构(Java语言)——BinaryHeap简单实现
- 自己写GoBinaryHead 二叉堆binaryheap实现优先队列(堆)
- 笔记
- 笔记
- 笔记
- 笔记
- 笔记
- 笔记
- 笔记
- 笔记
- 笔记
- 笔记
- BZOJ 2049 [Sdoi2008]Cave 洞穴勘测 LCT
- Can not find the tag library descriptor for "/struts-tags"
- Why Docker is Not Yet Succeeding Widely in Production
- java Socket多线程聊天程序(适合初学者)
- poj 2406 Power Strings (kmp)
- [笔记]binaryheap
- nginx的日志配置
- 蓝牙技术转载源码
- 杭电 2549 壮志难酬 水题
- uva 11040 - Add bricks in the wall
- Java线程:线程的同步与锁
- 深度搜索DFS hdu-1312
- C/C++,Windows/MFC, char, wchar_t, TCHAR 字符全总结 & c++字符串操作经验集
- 九度OJ 题目1006:ZOJ问题