Go 堆排序

Go 堆排序

本文主要介绍Golang的堆排序使用方法,通过container/heap实现堆相关的操作

堆因为其插入删除的操作时间复杂度低,因此优先队列通常是靠堆来实现的。Go的堆使用要实现heap包下的Interface接口

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

具体使用如下

package mainimport ("container/heap""fmt")// An MyHeap is a min-heap of ints.type people struct {name stringage  int}type MyHeap []peoplefunc (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}}
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部