go语言对heap方法对同优先级的元素遵循先进先出的顺序

前言

在 Go 语言的 container/heap 包中,heap.Pop() 方法并不保证对于同优先级的元素会遵循先进先出(FIFO)的顺序。堆的主要特性是根据优先级来组织元素,而不是根据插入顺序。

实现先进先出的堆

如果在处理同优先级元素时能够保持先进先出的顺序,你可以在堆的实现中引入一个额外的字段来记录插入顺序。例如,可以为每个元素添加一个索引或时间戳,并在 Less 方法中首先比较优先级,如果优先级相同,则比较插入顺序。

以下是一个示例,演示如何实现一个支持同优先级元素先进先出的堆:

package main

import (
	"container/heap"
	"fmt"
)

type Item struct {
	value    string // The value of the item
	priority int    // The priority of the item
	index    int    // The index of the item in the heap
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int {
	return len(pq)
}

func (pq PriorityQueue) Less(i, j int) bool {
	// 首先比较优先级,如果相同则比较插入顺序
	if pq[i].priority == pq[j].priority {
		return pq[i].index < pq[j].index // 保证先进先出
	}
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func main() {
	pq := &PriorityQueue{}
	heap.Init(pq)

	heap.Push(pq, &Item{value: "task1", priority: 2})
	heap.Push(pq, &Item{value: "task2", priority: 1})
	heap.Push(pq, &Item{value: "task3", priority: 2})

	for pq.Len() > 0 {
		item := heap.Pop(pq).(*Item)
		fmt.Printf("%s (priority: %d)\n", item.value, item.priority)
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值