-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpriorityqueue.go
94 lines (81 loc) · 1.98 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
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
package goschedule
import "fmt"
type PrioirityQueue struct {
jobs []*Job
size int
}
func newQueue(maxsize int) *PrioirityQueue {
pq := &PrioirityQueue{
jobs: []*Job{},
size: 0,
}
return pq
}
func (m *PrioirityQueue) leaf(index int) bool {
if index >= (m.size/2) && index <= m.size {
return true
}
return false
}
func (m *PrioirityQueue) parent(index int) int {
return (index - 1) / 2
}
func (m *PrioirityQueue) leftchild(index int) int {
return 2*index + 1
}
func (m *PrioirityQueue) rightchild(index int) int {
return 2*index + 2
}
func (m *PrioirityQueue) insert(newJob *Job) {
m.jobs = append(m.jobs, newJob)
m.size++
m.upHeapify(m.size - 1)
}
func (m *PrioirityQueue) swap(first, second int) {
temp := m.jobs[first]
m.jobs[first] = m.jobs[second]
m.jobs[second] = temp
}
func (m *PrioirityQueue) upHeapify(index int) {
for m.jobs[index].GetNextRunUnixNanoTime() < m.jobs[m.parent(index)].GetNextRunUnixNanoTime() {
m.swap(index, m.parent(index))
index = m.parent(index)
}
}
func (m *PrioirityQueue) downHeapify(current int) {
if m.leaf(current) {
return
}
smallest := current
leftChildIndex := m.leftchild(current)
rightRightIndex := m.rightchild(current)
if leftChildIndex < m.size && m.jobs[leftChildIndex].GetNextRunUnixNanoTime() < m.jobs[smallest].GetNextRunUnixNanoTime() {
smallest = leftChildIndex
}
if rightRightIndex < m.size && m.jobs[rightRightIndex].GetNextRunUnixNanoTime() < m.jobs[smallest].GetNextRunUnixNanoTime() {
smallest = rightRightIndex
}
if smallest != current {
m.swap(current, smallest)
m.downHeapify(smallest)
}
return
}
func (m *PrioirityQueue) buildMinHeap() {
for index := ((m.size / 2) - 1); index >= 0; index-- {
m.downHeapify(index)
}
}
func (m *PrioirityQueue) printJobIdentifiersSorted() {
for _, j := range m.jobs {
fmt.Println(j.GetIdentifier())
}
}
func (m *PrioirityQueue) remove() *Job {
top := m.jobs[0]
m.jobs[0] = m.jobs[m.size-1]
m.jobs = m.jobs[:(m.size)-1]
m.size--
m.downHeapify(0)
return top
}