-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpriority_queue.go
More file actions
62 lines (46 loc) · 1.06 KB
/
priority_queue.go
File metadata and controls
62 lines (46 loc) · 1.06 KB
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
package spellchecker
import "container/heap"
type priorityQueue struct {
items []Match
capacity int
}
func newPriorityQueue(capacity int) *priorityQueue {
return &priorityQueue{
items: make([]Match, 0, capacity),
capacity: capacity,
}
}
func (pq priorityQueue) Len() int { return len(pq.items) }
func (pq priorityQueue) Less(i, j int) bool {
return pq.items[i].Score < pq.items[j].Score
}
func (pq priorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
}
func (pq *priorityQueue) Push(x interface{}) {
item := x.(Match)
if len(pq.items) < pq.capacity {
pq.items = append(pq.items, item)
heap.Fix(pq, len(pq.items)-1)
return
}
if item.Score < pq.items[0].Score {
return
}
pq.items[0] = item
heap.Fix(pq, 0)
}
func (pq *priorityQueue) Pop() interface{} {
old := pq.items
n := len(old)
item := old[n-1]
pq.items = old[:n-1]
return item
}
func (pq *priorityQueue) DrainSorted() []Match {
out := make([]Match, pq.Len())
for i := len(out) - 1; i >= 0; i-- {
out[i] = heap.Pop(pq).(Match)
}
return out
}