golang中container/heap包源碼分析

學習golang不免須要分析源碼包中一些實現,下面就來講說container/heap包的源碼golang

 

heap的實現使用到了小根堆,下面先對堆作個簡單說明app

1. 堆概念  函數

  堆是一種通過排序的徹底二叉樹,其中任一非終端節點的數據值均不大於(或不小於)其左孩子和右孩子節點的值。
  最大堆和最小堆是 二叉堆的兩種形式。
  最大堆:根結點的鍵值是全部堆結點鍵值中最大者。
  最小堆:根結點的鍵值是全部堆結點鍵值中最小者。

2. heap學習

 樹的最小元素在根部,爲index 0.測試

 heap包對任意實現了heap接口的類型提供堆操做。ui

 heap是經常使用的實現優先隊列的方法。要建立一個優先隊列,實現一個具備使用(負的)優先級做爲比較的依據的Less方法的Heap接口,如此一來可用Push添加項目而用Pop取出隊列最高優先級的項目。this

// 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() 。 spa

同事還須要實現堆接口定義的兩個方法:Push(x interface{})   /  Pop() interface{}, 因此咱們要想使用heap定義一個堆, 只須要定義實現了這五個方法結構就能夠了。code

任何實現了本接口的類型均可以用於構建最小堆。最小堆能夠經過heap.Init創建,數據是遞增順序或者空的話也是最小堆。最小堆的約束條件是:htm

 !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 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-1]
    *h = old[0 : n-1]
    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{2, 1, 5}
    heap.Init(h)
    heap.Push(h, 3)
    fmt.Printf("minimum: %d\n", (*h)[0])
    for h.Len() > 0 {
        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-1]
    item.index = -1 // for safety
    *pq = old[0 : n-1]
    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": 3, "apple": 2, "pear": 4,
    }

    // Create a priority queue, put the items in it, and
    // establish the priority queue (heap) invariants.
    pq := make(PriorityQueue, len(items))
    i := 0
    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: 1,
    }
    heap.Push(&pq, item)
    pq.update(item, item.value, 5)

    // Take the items out; they arrive in decreasing priority order.
    for pq.Len() > 0 {
        item := heap.Pop(&pq).(*Item)
        fmt.Printf("%.2d:%s ", item.priority, item.value)
    }
    // Output:
    // 05:orange 04:pear 03:banana 02:apple
}

 

說明:測試源碼都是golang包裏面提供的, 有興趣能夠直接去查閱下golang源碼

相關文章
相關標籤/搜索