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