-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin_heap.go
116 lines (90 loc) · 2.19 KB
/
min_heap.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
package heap
import "errors"
type Item[TValue any] struct {
Value TValue
Priority int
}
type MinHeap[TValue any] struct {
items []Item[TValue]
}
func New[TValue any]() *MinHeap[TValue] {
return &MinHeap[TValue]{}
}
func parentIndex(i int) int {
return (i - 1) / 2
}
func leftChildIndex(i int) int {
return 2*i + 1
}
func rightChildIndex(i int) int {
return 2*i + 2
}
func (h *MinHeap[TValue]) siftUp(index int) {
for index > 0 {
parent := parentIndex(index)
if h.items[parent].Priority > h.items[index].Priority {
h.items[parent], h.items[index] = h.items[index], h.items[parent]
index = parent
} else {
break
}
}
}
func (h *MinHeap[TValue]) siftDown(index int) {
left := leftChildIndex(index)
right := rightChildIndex(index)
smallest := index
if left < len(h.items) && h.items[left].Priority < h.items[smallest].Priority {
smallest = left
}
if right < len(h.items) && h.items[right].Priority < h.items[smallest].Priority {
smallest = right
}
if smallest != index {
h.items[index], h.items[smallest] = h.items[smallest], h.items[index]
h.siftDown(smallest)
}
}
func (h *MinHeap[TValue]) Peek() *Item[TValue] {
if len(h.items) == 0 {
return nil
}
return &h.items[0]
}
func (h *MinHeap[TValue]) IsValid() bool {
for i := 1; i < len(h.items); i++ {
if h.items[parentIndex(i)].Priority > h.items[i].Priority {
return false
}
}
return true
}
func (h *MinHeap[TValue]) Insert(value TValue, priority int) {
h.items = append(h.items, Item[TValue]{Priority: priority, Value: value})
h.siftUp(len(h.items) - 1)
}
func (h *MinHeap[TValue]) Remove(index int) error {
if index < 0 || index >= len(h.items) {
return errors.New("index out of range")
}
h.items[index] = h.items[len(h.items)-1]
h.items = h.items[:len(h.items)-1]
h.siftDown(index)
return nil
}
func (h *MinHeap[TValue]) Update(index int, newPriority int) error {
if index < 0 || index >= len(h.items) {
return errors.New("index out of range")
}
oldPriority := h.items[index].Priority
h.items[index].Priority = newPriority
if newPriority < oldPriority {
h.siftUp(index)
} else {
h.siftDown(index)
}
return nil
}
func (h *MinHeap[TValue]) Items() []Item[TValue] {
return h.items
}