-
Notifications
You must be signed in to change notification settings - Fork 3
/
queue.go
117 lines (90 loc) · 2.04 KB
/
queue.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package codel
import (
"container/heap"
)
type queue []*prendezvouz
func (pq queue) Len() int { return len(pq) }
func (pq queue) 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 queue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *queue) Push(x interface{}) {
n := len(*pq)
item := x.(*prendezvouz)
item.index = n
*pq = append(*pq, item)
}
func (pq *queue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
func (pq *queue) lowestIndex() int {
old := *pq
n := len(old)
index := n / 2
lowestIndex := index
priority := maxInt
for i := index; i < n; i++ {
if old[i].priority < priority {
lowestIndex = i
priority = old[i].priority
}
}
return lowestIndex
}
type priorityQueue queue
func newQueue(capacity int) priorityQueue {
return priorityQueue(make([]*prendezvouz, 0, capacity))
}
func (pq *priorityQueue) Len() int {
return len(*pq)
}
func (pq *priorityQueue) Cap() int {
return cap(*pq)
}
func (pq *priorityQueue) push(r *prendezvouz) {
heap.Push((*queue)(pq), r)
}
func (pq *priorityQueue) Push(r *prendezvouz) bool {
// If we're under capacity, push it to the queue
if pq.Len() < pq.Cap() {
pq.push(r)
return true
}
if pq.Cap() == 0 {
return false
}
// otherwise, we need to check if this takes priority over the lowest element
lowestIndex := ((*queue)(pq)).lowestIndex()
last := (*pq)[lowestIndex]
if last.priority < r.priority {
(*pq)[lowestIndex] = r
// Fix the index
r.index = lowestIndex
heap.Fix((*queue)(pq), lowestIndex)
// For safety
last.index = -1
last.Drop()
return true
}
return false
}
func (pq *priorityQueue) Empty() bool {
return len(*pq) <= 0
}
func (pq *priorityQueue) Pop() prendezvouz {
r := heap.Pop((*queue)(pq)).(*prendezvouz)
return *r
}
func (pq *priorityQueue) Remove(r *prendezvouz) {
heap.Remove((*queue)(pq), r.index)
}