博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构-06-堆(Heap)
阅读量:2384 次
发布时间:2019-05-10

本文共 1819 字,大约阅读时间需要 6 分钟。

###Heap - 堆 一般情况下,通常指的是二叉堆,二叉堆是一个近似完全二叉树的数据结构,即披着二叉树羊皮的数组,故使用数组来实现较为便利。子结点的键值或索引总是小于(或者大于)它的父节点,且每个节点的左右子树又是一个二叉堆(大根堆或者小根堆)。根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。常被用作实现优先队列。

###特点

  1. 以数组表示,但是以完全二叉树的方式理解。
  2. 唯一能够同时最优地利用空间和时间的方法——最坏情况下也能保证使用 2N \log N2NlogN 次比较和恒定的额外空间。
  3. 在索引从0开始的数组中:
  • 父节点 i 的左子节点在位置(2*i+1)
  • 父节点 i 的右子节点在位置(2*i+2)
  • 子节点 i 的父节点在位置floor((i-1)/2)

###堆的基本操作 以大根堆为例,堆的常用操作如下。

  1. 最大堆调整(Max_Heapify):将堆的末端子节点作调整,使得子节点永远小于父节点
  2. 创建最大堆(Build_Max_Heap):将堆所有数据重新排序
  3. 堆排序(HeapSort):移除位在第一个数据的根节点,并做最大堆调整的递归运算
    其中步骤1是给步骤2和3用的。

输入图片说明

示例代码:

class MaxHeap:    def __init__(self, array=None):        if array:            self.heap = self._max_heapify(array)        else:            self.heap = []    def _sink(self, array, i):        # move node down the tree        left, right = 2 * i + 1, 2 * i + 2        max_index = i        if left < len(array) and array[left] > array[max_index]:            max_index = left        if right < len(array) and array[right] > array[max_index]:            max_index = right        if max_index != i:            array[i], array[max_index] = array[max_index], array[i]            self._sink(array, max_index)    def _swim(self, array, i):        # move node up the tree        if i == 0:            return        father = (i - 1) / 2        if array[father] < array[i]:            array[father], array[i] = array[i], array[father]            self._swim(array, father)    def _max_heapify(self, array):        for i in xrange(len(array) / 2, -1, -1):            self._sink(array, i)        return array    def push(self, item):        self.heap.append(item)        self._swim(self.heap, len(self.heap) - 1)    def pop(self):        self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0]        item = self.heap.pop()        self._sink(self.heap, 0)        return item

转载于:https://my.oschina.net/corwien/blog/693380

你可能感兴趣的文章
Virus Bulletin malware分析杂志以及paper
查看>>
Security Considerations for AppLocker
查看>>
Oracle Forensics t00ls
查看>>
JetLeak Vulnerability: Remote Leakage Of Shared Buffers In Jetty Web Server [CVE-2015-2080]
查看>>
zZ-ModSecurity Framework支持Web应用安全核心规则集
查看>>
zz-LDAP详解
查看>>
zZ-google-perftools 加速MySQL – TCMalloc
查看>>
apache 防DDOS脚本
查看>>
Linux黑客大曝光推荐工具
查看>>
使用syslog-ng 和stunnel 创建集中式安全日志服务器
查看>>
做人道理
查看>>
网友将电视剧潜伏当职场教科书 研究办公室政治
查看>>
graudit
查看>>
使用Hudson和FindBugs进行持续集成和代码检查
查看>>
New Tool: The PenTesters Framework (PTF) Released
查看>>
Detecting and Defending against PowerShell Shells
查看>>
NagVis实物监控工具
查看>>
nginx - low risk webdav destination bug
查看>>
Lessons Learned from Building and Running MHN, the World's Largest Crowdsourced Honeynet
查看>>
Logwatch Linux/Unix系统日志检测软件
查看>>