go标准库——优先级队列的实现

时间:2025-02-24 17:37:35
package heap_test // priorty_queue是以个带权值观念的queue,它允许加入新元素,移除旧元素,审视元素值等功能 import ( "container/heap" "fmt" "testing" ) // Item 是我们在优先队列中管理的东西 type Item struct { value string // The value of the item; arbitrary. priority int // 队列中项目的优先级 // The index is needed by update and is maintained by the methods. index int //在堆中的索引 } // 优先级队列 type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { // 我们希望 Pop 给我们最高而不是最低的优先级,所以我们使用比这里更大的优先级。 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] old[n-1] = nil // 避免内存泄漏 item.index = -1 // 为了安全 *pq = old[0 : n-1] return item } // update 修改队列中项目的优先级和值。 func (pq *PriorityQueue) update(item *Item, value string, priority int) { item.value = value item.priority = priority heap.Fix(pq, item.index) } // This example creates a PriorityQueue with some items, adds and manipulates an item, // and then removes the items in priority order. func Test_priorityQueue(t *testing.T) { // Some items and their priorities. items := map[string]int{ "banana": 3, "apple": 2, "pear": 4, } // Create a priority queue, put the items in it, and // establish the priority queue (heap) invariants. pq := make(PriorityQueue, len(items)) i := 0 for value, priority := range items { pq[i] = &Item{ value: value, priority: priority, index: i, } i++ } heap.Init(&pq) // 插入一个新项目,然后修改其优先级. item := &Item{ value: "orange", priority: 1, } heap.Push(&pq, item) pq.update(item, item.value, 5) // Take the items out; they arrive in decreasing priority order. for pq.Len() > 0 { item := heap.Pop(&pq).(*Item) fmt.Printf("%.2d:%s ", item.priority, item.value) } // Output: // 05:orange 04:pear 03:banana 02:apple }

相关文章