-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheaps.go
More file actions
53 lines (42 loc) · 1014 Bytes
/
heaps.go
File metadata and controls
53 lines (42 loc) · 1014 Bytes
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
package utils
import (
"cmp"
stdHeap "container/heap"
)
type heap[T cmp.Ordered] []T
func (h heap[T]) Len() int { return len(h) }
func (h heap[T]) Less(i, j int) bool { return h[i] < h[j] }
func (h heap[T]) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *heap[T]) Push(x any) {
*h = append(*h, x.(T))
}
func (h *heap[T]) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
type Heap[T cmp.Ordered] struct {
innerHeap *heap[T]
}
func (h *Heap[T]) Push(x T) {
stdHeap.Push(h.innerHeap, x)
}
func (h *Heap[T]) Pop() T {
return stdHeap.Pop(h.innerHeap).(T)
}
func (h *Heap[T]) IsEmpty() bool {
return h.innerHeap.Len() == 0
}
func NewHeap[T cmp.Ordered](initialSize ...int) *Heap[T] {
var innerHeap heap[T]
if len(initialSize) == 1 {
innerHeap = make([]T, initialSize[0])
} else if len(initialSize) == 2 {
innerHeap = make([]T, initialSize[0], initialSize[1])
} else {
innerHeap = make([]T, 0)
}
return &Heap[T]{innerHeap: &innerHeap}
}