這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
Go語言的OOP,介面,介面的組合,基礎庫的函數及介面如何抽象設計,
這些東西在Go的Heap源碼及示範例子處理中,都有很好的展示.
在"container/heap"中,它的介面是如下定義的:
type Interface interface { sort.Interface Push(x interface{}) // add x as element Len() Pop() interface{} // remove and return element Len() - 1. } 我不太明白為啥是這樣的設計,只好通過下面的方法來嘗試瞭解.
1. 通過測試例子,瞭解使用方式.
2. 試圖還原原始情境,即利用源碼整合實現了一個原始的堆排序
然後通過這兩者的對比,來慢慢體會.
container/heap的測試例子:
package mainimport ("container/heap""fmt""sort")// An IntHeap is a min-heap of ints.type IntHeap []intfunc (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 := *hn := 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 main() {h := &IntHeap{100,16,4,8,70,2,36,22,5,12}fmt.Println("\nHeap:")heap.Init(h)fmt.Printf("最小值: %d\n", (*h)[0])//for(Pop)依次輸出最小值,則相當於執行了HeapSortfmt.Println("\nHeap sort:")for h.Len() > 0 {fmt.Printf("%d ", heap.Pop(h))}//增加一個新值,然後輸出看看fmt.Println("\nPush(h, 3),然後輸出堆看看:")heap.Push(h, 3)for h.Len() > 0 {fmt.Printf("%d ", heap.Pop(h))}fmt.Println("\n使用sort.Sort排序:") h2 := IntHeap{100,16,4,8,70,2,36,22,5,12} sort.Sort(h2) for _,v := range h2 {fmt.Printf("%d ",v)}}/*輸出結果:-----------------------------------Heap:最小值: 2Heap sort:2 4 5 8 12 16 22 36 70 100Push(h, 3),然後輸出堆看看:3使用sort.Sort排序:2 4 5 8 12 16 22 36 70 100*/
自訂的類,實現相關介面後,交由heap.Init()去構建堆.
從堆中Pop()後,資料就被從heap中移除了.
升降序由Less()來決定.
自訂類也可以直接用Sort來排序,因為實現了相關介面.
再看下我手工整合實現的堆排序代碼:
package main//Heap//author:Xiong Chuan Liang//date:2015-2-4import ("fmt")var( heap = []int{100,16,4,8,70,2,36,22,5,12})func main(){fmt.Println("\n數組:")Print(heap) MakeHeap() fmt.Println("\n構建樹後:")Print(heap)fmt.Println("\n增加 90,30,1 :")Push(90)Push(30)Push(1)Print(heap)n := Pop()fmt.Println("\nPop出最小值(",n,")後:")Print(heap)fmt.Println("\nRemove()掉idx為3即值",heap[3-1],"後:")Remove(3)Print(heap)fmt.Println("\nHeapSort()後:")HeapSort()Print(heap)}func Print(arr []int){for _,v := range arr {fmt.Printf("%d ",v)}}//構建堆func MakeHeap(){n := len(heap)for i := n/2-1 ;i >= 0;i--{down(i, n)}}//由父節點至子節點依次建堆//parent : i//left child : 2*i+1//right child : 2*i+2func down(i,n int) {//構建最小堆,父小於兩子節點值for {j1 := 2*i + 1if j1 >= n || j1 < 0 { // j1 < 0 after int overflowbreak}//找出兩個節點中最小的(less: a<b)j := j1 // left childif j2 := j1 + 1; j2 < n && !Less(j1, j2) {j = j2 // = 2*i + 2 // right child}//然後與父節點i比較,如果父節點小於這個子節點最小值,則break,否則swapif !Less(j, i) {break}Swap(i, j)i = j}}//由子節點至父節點依次重建堆func up(j int) {for {i := (j - 1) / 2 // parent if i == j || !Less(j, i) { //less(子,父) !Less(9,5) == true //父節點小於子節點,符合最小堆條件,breakbreak}//子節點比父節點小,互換Swap(i, j)j = i}}func Push(x interface{}){heap = append(heap, x.(int))up(len(heap)-1)return }func Pop() interface{} {n := len(heap) - 1Swap(0, n)down(0, n)old :=heapn = len(old)x := old[n-1]heap = old[0 : n-1]return x}func Remove(i int) interface{} {n := len(heap) - 1if n != i {Swap(i, n)down(i, n)up(i)}return Pop()}func Less(a,b int)bool{return heap[a] < heap[b]func Swap(a,b int){heap[a],heap[b] = heap[b],heap[a]}func HeapSort(){//升序 Less(heap[a] > heap[b])//最大堆//降序 Less(heap[a] < heap[b])//最小堆for i := len(heap)-1 ;i > 0;i--{//移除頂部元素到數組末尾,然後剩下的重建堆,依次迴圈Swap(0, i)down(0, i)}}/*輸出結果:-----------------------------------數組:100 16 4 8 70 2 36 22 5 12構建樹後:2 5 4 8 12 100 36 22 16 70增加 90,30,1 :1 5 2 8 12 4 36 22 16 70 90 100 30Pop出最小值( 1 )後:2 5 4 8 12 30 36 22 16 70 90 100Remove()掉idx為3即值 4 後:4 5 8 16 12 30 36 22 100 70 90HeapSort()後:100 90 70 36 30 22 16 12 8 5 4*/
兩相對比之後發現,container/heap 競然,真的,
僅且只是封裝了一個堆而已.
把那些不確定的,各種需要定製的東西,都交給了使用者去實現.
它僅僅只負責最核心的堆這部份的東西.
這樣基礎庫清爽了,使用堆時也不會再感到縛手縛腳了.
MAIL: xcl_168@aliyun.com
BLOG:http://blog.csdn.ent/xcl168