用container/heap实现一个最小堆

很少用container/heap这个工具,今天看到别人用来实现一个最小堆,感觉很有意思哈。代码如下:

type Request struct {
	fn    func() int
	data  []byte
	op    int
	c     chan int
}

type Worker struct {
	req     chan Request
	pending int
	index   int
	done    chan struct{}
}

type Pool []*Worker

func (p Pool) Len() int {
	return len(p)
}
func (p Pool) Less(i, j int) bool {
	return p[i].pending < p[j].pending
}

func (p Pool) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
	p[i].index = i
	p[j].index = j
}

func (p *Pool) Push(x interface{}) {
	n := len(*p)
	item := x.(*Worker)
	item.index = n
	*p = append(*p, item)
}

func (p *Pool) Pop() interface{} {
	old := *p
	n := len(*p)
	item := old[n-1]
	//item.index = -1
	*p = old[:n-1]
	return item

测试代码:

func TestHeap(t *testing.T) {
	pool := new(Pool)
	for i := 0; i < 4; i++ {
		work := &Worker{
			req:     make(chan Request, MaxQueue),
			pending: rand.Intn(100),
			index:   i,
		}
		log.Println("pengding", work.pending, "i", i)
		heap.Push(pool, work)
	}

	heap.Init(pool)
	log.Println("init heap success")
	work := &Worker{
		req:     make(chan Request, MaxQueue),
		pending: 50,
		index:   4,
	}
	heap.Push(pool, work)
	log.Println("Push worker: pending", work.pending)
	for pool.Len() > 0 {
		worker := heap.Pop(pool).(*Worker)
		log.Println("Pop worker:index", worker.index, "pending", worker.pending)
	}
}

(全文完)

参考链接:

https://mp.weixin.qq.com/s?__biz=MzI3MjU4Njk3Ng==&mid=2247483835&idx=1&sn=c07e85efdcc74e2ca5203aa58cbe078d&chksm=eb310034dc468922b7a08c93be7dfcbdb2a65e41f512c1fd4b2fc3788fb77603009cf366b62b&scene=27#wechat_redirect

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值