-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.go
55 lines (43 loc) · 944 Bytes
/
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
package main
// imports heap package to enable heap sorting methods
import hp "container/heap"
type path struct {
value int
houses []string
}
type minPath []path
func (h minPath) Len() int {
return len(h)
}
// This function handles the phase of heap sorting that selects the lesser value
func (h minPath) Less(i, j int) bool {
return h[i].value < h[j].value
}
// This function handles the swap phase of heap sorting
func (h minPath) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *minPath) Push(x interface{}) {
*h = append(*h, x.(path))
}
// This function removes the highest sorted value.
func (h *minPath) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
type heap struct {
values *minPath
}
func newHeap() *heap {
return &heap{values: &minPath{}}
}
func (h *heap) push(p path) {
hp.Push(h.values, p)
}
func (h *heap) pop() path {
i := hp.Pop(h.values)
return i.(path)
}