-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.go
65 lines (52 loc) · 1.09 KB
/
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
package pyramid
import (
"container/heap"
)
// Heap
// type which manages the heap list of any type.
type Heap[T any] struct {
// heap has a queue to manage the items init
queue Queue[T]
}
// Push
// items to heap.
func (h *Heap[T]) Push(value any) {
heap.Push(&h.queue, value)
}
// Pop
// items from list.
func (h *Heap[T]) Pop() any {
return heap.Pop(&h.queue)
}
// Length
// heap length.
func (h *Heap[T]) Length() int {
return h.queue.Len()
}
// Update
// the queue list.
func (h *Heap[T]) Update(old any, new any, ef equalFunction[T]) {
index := h.find(old, ef)
if index == -1 {
return
}
h.queue.update(h.queue.list[index], new.(T))
}
func (h *Heap[T]) find(object any, equalFunction equalFunction[T]) int {
for index, obj := range h.queue.list {
if equalFunction(obj.value, object.(T)) {
return index
}
}
return -1
}
// NewHeap
// creates a new heap of any type.
func NewHeap[T any](compareFunction compareFunction[T]) Heap[T] {
var pq Heap[T]
// setting the compare function
pq.queue.compareFunction = compareFunction
// registering the
heap.Init(&pq.queue)
return pq
}