Jenkins的安裝與部署
阿新 • • 發佈:2022-05-16
本文主要介紹Golang的堆排序使用方法,通過container/heap實現堆相關的操作
堆因為其插入刪除的操作時間複雜度低,因此優先佇列通常是靠堆來實現的。Go的堆使用要實現heap包下的Interface介面
type Interface interface {
sort.Interface
Push(x any) // add x as element Len()
Pop() any // remove and return element Len() - 1.
}
具體使用如下
package main import ( "container/heap" "fmt" ) // An MyHeap is a min-heap of ints. type people struct { name string age int } type MyHeap []people func (h MyHeap) Len() int { return len(h) } func (h MyHeap) Less(i, j int) bool { if h[i].age == h[j].age { // 先按age從大排序,再按名字從小排序 return h[i].name < h[j].name } else { return h[i].age > h[j].age } } func (h MyHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *MyHeap) Push(x interface{}) { *h = append(*h, x.(people)) } func (h *MyHeap) Pop() interface{} { res := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return res } func main() { h := &MyHeap{people{"h", 2}, people{"h", 3}, people{"a", 1}} heap.Init(h) fmt.Printf("%v ", h) //&[{h 3} {h 2} {a 1}] heap.Push(h, people{"a", 4}) fmt.Printf("%v ", h)// &[{a 4} {h 3} {a 1} {h 2}] for h.Len() > 0 { fmt.Printf("%v ", heap.Pop(h)) }//{a 4} {h 3} {h 2} {a 1} }