/
arrayheap.go
61 lines (47 loc) · 894 Bytes
/
arrayheap.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
package misc
import "container/heap"
type Comparable interface {
Less(other Comparable) bool
}
type ArrayHeap []Comparable
func (h *ArrayHeap) Len() int {
return len(*h)
}
func (h *ArrayHeap) Less(i, j int) bool {
return (*h)[i].Less((*h)[j])
}
func (h *ArrayHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *ArrayHeap) Push(x interface{}) {
*h = append(*h, x.(Comparable))
}
func (h *ArrayHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func Top(h *ArrayHeap) Comparable {
return (*h)[0]
}
func Pop(h *ArrayHeap) Comparable {
x := Top(h)
heap.Pop(h)
return x
}
func Push(h *ArrayHeap, x Comparable) {
heap.Push(h, x)
}
func Init(h *ArrayHeap) {
heap.Init(h)
}
func Remove(h *ArrayHeap, i int) Comparable {
x := (*h)[i]
heap.Remove(h, i)
return x
}
func Len(h *ArrayHeap) int {
return len(*h)
}