-
Notifications
You must be signed in to change notification settings - Fork 16
/
collection.go
79 lines (68 loc) · 1.74 KB
/
collection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package pgo
import "container/heap"
// An Item is something we manage in a Priority queue.
type Item struct {
Value string // The Value of the item; arbitrary.
Priority int // The Priority of the item in the queue.
// The Index is needed by update and is maintained by the heap.Interface methods.
Index int // The Index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, Priority so we use greater than here.
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{} {
nLen := pq.Len() - 1
pq.Swap(0, nLen)
pq.down(0, nLen)
// ---
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.Index = -1 // for safety
*pq = old[0 : n-1]
return item
}
func (pq *PriorityQueue) down(i0, n int) bool {
i := i0
for {
j1 := 2*i + 1
if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && pq.Less(j2, j1) {
j = j2 // = 2*i + 2 // right child
}
if !pq.Less(j, i) {
break
}
pq.Swap(i, j)
i = j
}
return i > i0
}
//Update modifies the Priority and Value of an Item in the queue.
func (pq *PriorityQueue) Update(item *Item, value string, priority int) {
item.Value = value
item.Priority = priority
heap.Fix(pq, item.Index)
}
func (pq *PriorityQueue) Init() {
heap.Init(pq)
}