/
priorityqueue.go
executable file
·58 lines (49 loc) · 1.21 KB
/
priorityqueue.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
// Copyright 2016 Patrick Brosi
// Authors: [email protected]
//
// Use of this source code is governed by a GPL v2
// license that can be found in the LICENSE file
package processors
type Item struct {
value int
priority float32
index int
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue struct {
Items []*Item
Pqids []int
}
func NewPriorityQueue(len int) PriorityQueue {
return PriorityQueue{
Items: make([]*Item, len),
Pqids: make([]int, len),
}
}
func (pq PriorityQueue) Len() int { return len(pq.Items) }
func (pq PriorityQueue) Less(i, j int) bool {
return pq.Items[i].priority > pq.Items[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq.Items[i], pq.Items[j] = pq.Items[j], pq.Items[i]
pq.Items[i].index = i
pq.Items[j].index = j
pq.Pqids[pq.Items[i].value] = i
pq.Pqids[pq.Items[j].value] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(pq.Items)
item := x.(*Item)
item.index = n
pq.Items = append(pq.Items, item)
pq.Pqids = append(pq.Pqids, x.(*Item).value)
}
func (pq *PriorityQueue) Pop() interface{} {
old := pq.Items
n := len(old)
item := old[n-1]
old[n-1] = nil
item.index = -1
pq.Items = old[0 : n-1]
return item
}