Heap

What will be printed when the code below is executed?

  1. package main
  2. import (
  3. "container/heap"
  4. "fmt"
  5. )
  6. type IntHeap []int
  7. func (h IntHeap) Len() int { return len(h) }
  8. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  9. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  10. func (h *IntHeap) Push(x interface{}) {
  11. *h = append(*h, x.(int))
  12. }
  13. func (h *IntHeap) Pop() interface{} {
  14. old := *h
  15. n := len(old)
  16. x := old[n-1]
  17. *h = old[0 : n-1]
  18. return x
  19. }
  20. func main() {
  21. h := &IntHeap{2, 1, 5}
  22. heap.Init(h)
  23. for h.Len() > 0 {
  24. fmt.Printf("%d ", heap.Pop(h))
  25. }
  26. }

Answer

  1. 1 2 5