堆定义
根据维基百科:
堆是一种特别的完全二叉树。若是满足以下特性,即可称为堆:“给定堆中任意节点P和C,若P是C的父节点,那么P的值会小于等于(或大于等于)C的值”。若父节点的值恒小于等于子节点的值,此堆称为最小堆(min heap);反之,若父节点的值恒大于等于子节点的值,此堆称为最大堆(max heap)。
在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。
堆分为最大堆和最小堆。
堆的常用方法:
- 构建优先队列
- 支持堆排序
- 快速找出一个集合中的最小值(或者最大值)
完全二叉树和满二叉树区别如下:
由于堆是完全二叉树,所以可以用顺序数组来表示,如下图。
container/heap
定义
heap定义了heap.Interface,并且提供堆方法:Init/Push/Pop/Remove/Fix。
container/heap
为最小堆,即每个节点的值都小于它的子树的所有元素的值(A heap is a tree with the property that each node is the minimum-valued node in its subtree)。
Package heap provides heap operations for any type that implements heap.Interface. A heap is a tree with the property that each node is the minimum-valued node in its subtree. The minimum element in the tr