-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpriorityQueue.go
More file actions
89 lines (76 loc) · 1.75 KB
/
priorityQueue.go
File metadata and controls
89 lines (76 loc) · 1.75 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
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
package datastructures
type PriorityQueue struct {
items []int
}
func (q *PriorityQueue) Size() int {
return len(q.items)
}
func NewPriorityQueue() *PriorityQueue {
return &PriorityQueue{items: make([]int,0)}
}
func (q *PriorityQueue) reArrange() {
NewMaxHeap(q.items).BuildMaxHeap()
}
func (q *PriorityQueue) IsEmpty() bool{
return q.Size() == 0
}
func (q *PriorityQueue) Peak() int {
if q.IsEmpty(){
panic("No item is in the queue.")
}
return q.items[0]
}
func (q *PriorityQueue) Dequeue() int {
if q.IsEmpty(){
panic("No item is in the queue.")
}
if q.IsEmpty(){
panic("No item is in the queue.")
}
max := q.items[0]
swapArrayElements(q.items, 0, q.Size()-1)
q.items = q.items[:q.Size()-1]
q.reArrange()
return max
}
func (q *PriorityQueue) UpdateValue(index int, value int){
if index < q.Size(){
q.items[index] = value
parentIndex := (index+1)/2-1
for index >= 0 && q.items[parentIndex] < q.items[index]{
swapArrayElements(q.items, index, parentIndex)
index = parentIndex
}
}
}
func (q *PriorityQueue) Enqueue(item int) {
if q.IsEmpty(){
q.items = append(q.items, item)
} else {
q.items = append(q.items, item)
q.reArrange()
}
}
func (q *PriorityQueue) EnqueueItems(items []int) {
for _, item := range items{
q.Enqueue(item)
}
}
func (q *PriorityQueue) Remove(index int) int{
if q.IsEmpty(){
panic("No item is in the queue.")
}
item := q.items[index]
q.items[index] = q.items[q.Size()-1]
q.items = q.items[:q.Size()-1]
q.reArrange()
return item
}
//Swap first and second index elements in items array
func swapArrayElements(items []int, first int, second int) {
if first < len(items) && second < len(items) && first != second {
temp := items[first]
items[first] = items[second]
items[second] = temp
}
}