...
Source file
src/container/heap/example_intheap_test.go
1
2
3
4
5
6 package heap_test
7
8 import (
9 "container/heap"
10 "fmt"
11 )
12
13
14 type IntHeap []int
15
16 func (h IntHeap) Len() int { return len(h) }
17 func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
18 func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
19
20 func (h *IntHeap) Push(x any) {
21
22
23 *h = append(*h, x.(int))
24 }
25
26 func (h *IntHeap) Pop() any {
27 old := *h
28 n := len(old)
29 x := old[n-1]
30 *h = old[0 : n-1]
31 return x
32 }
33
34
35
36 func Example_intHeap() {
37 h := &IntHeap{2, 1, 5}
38 heap.Init(h)
39 heap.Push(h, 3)
40 fmt.Printf("minimum: %d\n", (*h)[0])
41 for h.Len() > 0 {
42 fmt.Printf("%d ", heap.Pop(h))
43 }
44
45
46
47 }
48
View as plain text