Go 堆排序

本文主要介绍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}
}
posted @   Notomato  阅读(166)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示