1
// Copyright 2012 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
5
// This example demonstrates a priority queue built using the heap interface.
13
// An Item is something we manage in a priority queue.
15
value string // The value of the item; arbitrary.
16
priority int // The priority of the item in the queue.
17
// The index is needed by update and is maintained by the heap.Interface methods.
18
index int // The index of the item in the heap.
21
// A PriorityQueue implements heap.Interface and holds Items.
22
type PriorityQueue []*Item
24
func (pq PriorityQueue) Len() int { return len(pq) }
26
func (pq PriorityQueue) Less(i, j int) bool {
27
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
28
return pq[i].priority > pq[j].priority
31
func (pq PriorityQueue) Swap(i, j int) {
32
pq[i], pq[j] = pq[j], pq[i]
37
func (pq *PriorityQueue) Push(x interface{}) {
41
*pq = append(*pq, item)
44
func (pq *PriorityQueue) Pop() interface{} {
48
item.index = -1 // for safety
53
// update modifies the priority and value of an Item in the queue.
54
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
55
heap.Remove(pq, item.index)
57
item.priority = priority
61
// This example inserts some items into a PriorityQueue, manipulates an item,
62
// and then removes the items in priority order.
63
func Example_priorityQueue() {
64
// Some items and their priorities.
65
items := map[string]int{
66
"banana": 3, "apple": 2, "pear": 4,
69
// Create a priority queue and put the items in it.
70
pq := &PriorityQueue{}
72
for value, priority := range items {
80
// Insert a new item and then modify its priority.
86
pq.update(item, item.value, 5)
88
// Take the items out; they arrive in decreasing priority order.
90
item := heap.Pop(pq).(*Item)
91
fmt.Printf("%.2d:%s ", item.priority, item.value)
94
// 05:orange 04:pear 03:banana 02:apple