-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.go
70 lines (57 loc) · 1.34 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
package queue
// Queue is the priority queue based on insertion sort
type Queue[T Item[T]] []T
// NewQueue creates an instance of the priority queue
func NewQueue[T Item[T]]() Queue[T] {
return make(Queue[T], 0)
}
// Len returns the length of the queue
func (q *Queue[T]) Len() int {
return len(*q)
}
// Index returns the element at the specified index, if any.
// NOTE: panics if out of bounds
func (q *Queue[T]) Index(index int) T {
return (*q)[index]
}
// Push adds a new element to the priority queue
func (q *Queue[T]) Push(item T) {
*q = append(*q, item)
for i := len(*q) - 1; i > 0; i-- {
if (*q)[i].Less((*q)[i-1]) {
(*q)[i], (*q)[i-1] = (*q)[i-1], (*q)[i]
} else {
// queue is sorted, no need to continue iteration
break
}
}
}
// Fix makes sure the priority queue is properly sorted
func (q *Queue[T]) Fix() {
for i := 1; i < len(*q); i++ {
for j := i - 1; j >= 0; j-- {
if (*q)[j].Less((*q)[j+1]) {
break
}
(*q)[j], (*q)[j+1] = (*q)[j+1], (*q)[j]
}
}
}
// PopFront removes the first element in the queue, if any
func (q *Queue[T]) PopFront() *T {
if len(*q) == 0 {
return nil
}
el := (*q)[0]
*q = (*q)[1:]
return &el
}
// PopBack removes the last element in the queue, if any
func (q *Queue[T]) PopBack() *T {
if len(*q) == 0 {
return nil
}
el := (*q)[len(*q)-1]
*q = (*q)[:len(*q)-1]
return &el
}