Golang的Heap使用之謎

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Go語言的官方package裡面提供了"container/heap",在該package裡面定義了Heap(堆)這一資料結構的使用介面。只要自訂的資料類型實現了標準介面,可以很方便的對自訂的資料類型在堆中進行排序了。

堆結構的介面為:

type Interface interface {sort.InterfacePush(x interface{}) // add x as element Len()Pop() interface{}   // remove and return element Len() - 1.}

同時sort.Interface介面為:

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)}

因此為了使用自訂的堆結構,需要定義5個介面函數。

在實踐中期望構造一個使用堆排序的定時器隊列,能夠按照堆頂的元素快速獲得最近的任務觸發時間:

type element struct {TaskId    stringExpire    time.Time...}type eleHeap []*element

構造自訂的堆結構介面:

func (h eleHeap) Len() int           { return len(h) }func (h eleHeap) Less(i, j int) bool { return h[i].Expire.Before(h[j].Expire) }func (h eleHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }func (h *eleHeap) Push(x interface{}) {// Push and Pop use pointer receivers because they modify the slice's length,// not just its contents.*h = append(*h, x.(*element))}func (h *eleHeap) Pop() interface{} {old := *hn := len(old)x := old[n-1]// 為什麼Pop是取slice最末元素?*h = old[0 : n-1]   // 難道Golang的堆不是最小堆嗎?return x}

在此之後就可以使用Heap的公用函數來對自訂的堆結構進行Pop和Push操作了。

to := time.NewTimer(WaitInterval)hp := &eleHeap{} // 定義變數heap.Init(hp) // 堆結構初始化for {select {case ele := <-TaskChan:heap.Push(hp, ele) // 入堆to.Reset(0)case <-to.C:for hp.Len() != 0 {ele, ok := heap.Pop(hp).(*element) // 出堆if ok {if time.Now().Before(ele.Expire) {heap.Push(hp, ele) // 時辰未到,再次入堆to.Reset(ele.Expire.Sub(now))break}// time expired, do task...}}}}}

在使用堆的過程中,對於為何在自訂的Pop過程中,取出的是隊列中最末元素有些不解。自訂的Push過程也是將元素放在最末,那麼Pop過程理所應當從隊列頭部取出經過上浮、下沉操作後堆中最小(大)的元素。經過查看"container/heap"的源碼,終於揭開了這一謎題。

首先看一下堆的上浮、下沉操作:

func up(h Interface, j int) {for {i := (j - 1) / 2 // parentif i == j || !h.Less(j, i) {break}// 在上浮過程中,從較大的節點j開始,與其父節點進行比較// 若不小於其父節點,則與其父節點進行交換h.Swap(i, j)j = i}}func down(h Interface, i0, n int) bool {i := i0for {j1 := 2*i + 1if j1 >= n || j1 < 0 { // j1 < 0 after int overflowbreak}j := j1 // left childif j2 := j1 + 1; j2 < n && !h.Less(j1, j2) {j = j2 // = 2*i + 2  // right child}if !h.Less(j, i) {break}// 在下沉過程中,從較小的i0節點開始,與其兩個子節點進行比較// 若小於其中一個子節點,則與較小的子節點進行交換h.Swap(i, j)i = j}return i > i0}

上浮和下沉過程還是十分標準的,再看一下Push和Pop過程:

func Push(h Interface, x interface{}) {h.Push(x)        // 使用自訂的Push介面,將元素放入隊列尾部up(h, h.Len()-1) // 將新放入的元素進行上浮操作}func Pop(h Interface) interface{} {n := h.Len() - 1h.Swap(0, n)     // 交換隊列中頭和尾元素down(h, 0, n)    // 將原隊列的尾元素在h.Len() - 1的新隊列中進行下沉return h.Pop()   // 彈出交換後的尾元素}

由此可見,對於自訂Pop函數理解的錯誤還是因為自身對於堆結構的思維定勢導致的。如果Heap.Pop過程中,先獲得頭元素的值,再將尾元素放入隊列頭進行下沉,則自訂的Pop才是返回隊列頭元素。

真相只有一個~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.