-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap_example.go
38 lines (33 loc) · 916 Bytes
/
heap_example.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
package main
// An IntHeap is a min-heap of ints.
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
//func main() {
//// h := &IntHeap{2, 1, 5}
// h := &IntHeap{}
//// heap.Init(h)
// heap.Push(h, 2)
// heap.Push(h, 1)
// heap.Push(h, 5)
// heap.Push(h, 3)
// fmt.Printf("minimum: %d\n", (*h)[0])
// for h.Len() > 0 {
// fmt.Printf("%d ", heap.Pop(h))
// }
//}