学习golang难免需要分析源码包中一些实现,下面就来说说container/heap包的源码

heap的实现使用到了小根堆,下面先对堆做个简单说明

1. 堆概念  

  堆是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于(或不小于)其左孩子和右孩子节点的值。
  最大堆和最小堆是二叉堆的两种形式。
  最大堆:根结点的键值是所有堆结点键值中最大者。
  最小堆:根结点的键值是所有堆结点键值中最小者。

2. heap

 树的最小元素在根部,为index 0.

 heap包对任意实现了heap接口的类型提供堆操作。

 heap是常用的实现优先队列的方法。要创建一个优先队列,实现一个具有使用(负的)优先级作为比较的依据的Less方法的Heap接口,如此一来可用Push添加项目而用Pop取出队列最高优先级的项目。

// Any type that implements heap.Interface may be used as a
// min-heap with the following invariants (established after
// Init has been called or if the data is empty or sorted):
//
// !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
//
// Note that Push and Pop in this interface are for package heap's
// implementation to call. To add and remove things from the heap,
// use heap.Push and heap.Pop.
type Interface interface {
sort.Interface
Push(x interface{}) // add x as element Len()
Pop() interface{} // remove and return element Len() - 1.
}
// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}

根据上面interface的定义,可以看出这个堆结构继承自sort.Interface, 而sort.Interface,需要实现三个方法:Len(), Less() , Swap() 。

同事还需要实现堆接口定义的两个方法:Push(x interface{})   /  Pop() interface{}, 所以我们要想使用heap定义一个堆, 只需要定义实现了这五个方法结构就可以了。

任何实现了本接口的类型都可以用于构建最小堆。最小堆可以通过heap.Init建立,数据是递增顺序或者空的话也是最小堆。最小堆的约束条件是:

 !h.Less(j, i) for  <= i < h.Len() and *i+ <= j <= *i+ and j < h.Len()

注意接口的Push和Pop方法是供heap包调用的,请使用heap.Push和heap.Pop来向一个堆添加或者删除元素。

以下是heap导出的方法:

func Fix(h Interface, i int)            //在修改第i个元素后,调用本函数修复堆,比删除第i个元素后插入新元素更有效率。复杂度O(log(n)),其中n等于h.Len()。
func Init(h Interface)              //初始化一个堆。一个堆在使用任何堆操作之前应先初始化。Init函数对于堆的约束性是幂等的(多次执行无意义),并可能在任何时候堆的约束性被破坏时被调用。本函数复杂度为O(n),其中n等于h.Len()。
func Pop(h Interface) interface{}       //删除并返回堆h中的最小元素(不影响约束性)。复杂度O(log(n)),其中n等于h.Len()。该函数等价于Remove(h, 0)。
func Push(h Interface, x interface{})     //向堆h中插入元素x,并保持堆的约束性。复杂度O(log(n)),其中n等于h.Len()。
func Remove(h Interface, i int) interface{} //删除堆中的第i个元素,并保持堆的约束性。复杂度O(log(n)),其中n等于h.Len()。

实例:

1. 包含int的最小堆

// This example demonstrates an integer heap built using the heap interface.
package heap_test import (
"container/heap"
"fmt"
) // An IntHeap is a min-heap of ints.
type IntHeap []int func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
} func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-]
*h = old[ : n-]
return x
} // This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
func Example_intHeap() {
h := &IntHeap{, , }
heap.Init(h)
heap.Push(h, )
fmt.Printf("minimum: %d\n", (*h)[])
for h.Len() > {
fmt.Printf("%d ", heap.Pop(h))
}
// Output:
// minimum: 1
// 1 2 3 5
}

2. 用heap创建一个优先级队列

// This example demonstrates a priority queue built using the heap interface.
package heap_test import (
"container/heap"
"fmt"
) // An Item is something we manage in a priority queue.
type Item struct {
value string // The value of the item; arbitrary.
priority int // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
} // A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
return pq[i].priority > pq[j].priority
} func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
} func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
} func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-]
item.index = - // for safety
*pq = old[ : n-]
return item
} // update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
} // This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func Example_priorityQueue() {
// Some items and their priorities.
items := map[string]int{
"banana": , "apple": , "pear": ,
} // Create a priority queue, put the items in it, and
// establish the priority queue (heap) invariants.
pq := make(PriorityQueue, len(items))
i :=
for value, priority := range items {
pq[i] = &Item{
value: value,
priority: priority,
index: i,
}
i++
}
heap.Init(&pq) // Insert a new item and then modify its priority.
item := &Item{
value: "orange",
priority: ,
}
heap.Push(&pq, item)
pq.update(item, item.value, ) // Take the items out; they arrive in decreasing priority order.
for pq.Len() > {
item := heap.Pop(&pq).(*Item)
fmt.Printf("%.2d:%s ", item.priority, item.value)
}
// Output:
// 05:orange 04:pear 03:banana 02:apple
}

说明:测试源码都是golang包里面提供的, 有兴趣可以直接去查阅下golang源码

golang中container/heap包源码分析的更多相关文章

  1. golang中container/list包源码分析

    golang源码包中container/list实际上是一个双向链表 提供链表的一些基本操作,下面就结合定义和接口进行下说明 1. 定义 // Element is an element of a l ...

  2. RocketMQ中PullConsumer的启动源码分析

    通过DefaultMQPullConsumer作为默认实现,这里的启动过程和Producer很相似,但相比复杂一些 [RocketMQ中Producer的启动源码分析] DefaultMQPullCo ...

  3. Netty中NioEventLoopGroup的创建源码分析

    NioEventLoopGroup的无参构造: public NioEventLoopGroup() { this(0); } 调用了单参的构造: public NioEventLoopGroup(i ...

  4. RocketMQ中Broker的启动源码分析(一)

    在RocketMQ中,使用BrokerStartup作为启动类,相较于NameServer的启动,Broker作为RocketMQ的核心可复杂得多 [RocketMQ中NameServer的启动源码分 ...

  5. RocketMQ中Broker的启动源码分析(二)

    接着上一篇博客  [RocketMQ中Broker的启动源码分析(一)] 在完成准备工作后,调用start方法: public static BrokerController start(Broker ...

  6. RocketMQ中Broker的消息存储源码分析

    Broker和前面分析过的NameServer类似,需要在Pipeline责任链上通过NettyServerHandler来处理消息 [RocketMQ中NameServer的启动源码分析] 实际上就 ...

  7. JDK中String类的源码分析(二)

    1.startsWith(String prefix, int toffset)方法 包括startsWith(*),endsWith(*)方法,都是调用上述一个方法 public boolean s ...

  8. Springboot中mybatis执行逻辑源码分析

    Springboot中mybatis执行逻辑源码分析 在上一篇springboot整合mybatis源码分析已经讲了我们的Mapper接口,userMapper是通过MapperProxy实现的一个动 ...

  9. sklearn包源码分析(一)--neighbors

    python如何查看内置函数的用法及其源码? 在anaconda的安装目录下,有一块会放着我们安装的所有包,在里面可以找到所有的包 找到scikit learn包,进入 这里面又有了多个子包,每个子包 ...

随机推荐

  1. TextUtils使用

    public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceS ...

  2. One-Way Reform

    One-Way Reform time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...

  3. Filter 解决web网页跳转乱码

    为什么采用filter实现了字符集的统一编码 问题: 为什么会有字符集编码的问题呢?对于Java Web应用,使用Tomcat容器获取和传递的参数(request.getParameter())默认是 ...

  4. linux视频学习3(shell和网络)

    1.shell的学习. shell的种类比较多,主要有三种: /bin/sh, /bin/csh, /bin/ksh. 查看当前使用的是哪种shell : 命令env (显示当前操作系统的环境变量). ...

  5. java数据结构之二叉树的实现

    java二叉树的简单实现,可以简单实现深度为n的二叉树的建立,二叉树的前序遍历,中序遍历,后序遍历输出. /** *数据结构之树的实现 *2016/4/29 * **/ package cn.Link ...

  6. 转:通过ant来批量执行jmeter脚本,并生成报告(附: 生成报告时报“Content is not allowed in prolog”这个错误的解决方案)

    最近在使用jmeter写脚本来进行测试,最终写了很多份脚本,然后,就在想,这么多脚本,我不可能一个一个的手动去点啊,有没有什么办法来批量运行Jmeter脚本呢? 这个时候,自然而然地想到了万能的ant ...

  7. maven学习笔记 1

    1    概述 1.1 Maven是什么 1.2 为什么要用Maven 2    怎么用Maven 2.1 Maven仓库 2.2 Maven安装 2.3 Eclipse插件 2.4 Maven常用命 ...

  8. FileReader和BufferedReader的区别

    1.FileReader不能一行行读 FileReader fr = null; try { fr = new FileReader(new File(path)); StringBuffer str ...

  9. java数据类型,hibernate数据类型,标准sql数据类型之间的对应表

    Hibernate API简介 其接口分为以下几类: l         提供访问数据库的操作的接口: l         用于配置Hibernate的接口: l         回调接口 l     ...

  10. poj 1837 Balance 动态规划 (经典好题,很锻炼思维)

    题目大意:给你一个天平,并给出m个刻度,n个砝码,刻度的绝对值代表距离平衡点的位置,并给出每个砝码的重量.达到平衡状态的方法有几种. 题目思路:首先我们先要明确dp数组的作用,dp[i][j]中,i为 ...