heap_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package sortutil
  10. import (
  11. "bytes"
  12. "container/heap"
  13. "fmt"
  14. "testing"
  15. )
  16. func TestIntHeap(t *testing.T) {
  17. h := &IntHeap{2, 1, 5}
  18. heap.Init(h)
  19. heap.Push(h, 3)
  20. heap.Push(h, 8)
  21. if (*h)[0] != 1 {
  22. t.Error("Unexpected minimum:", (*h)[0])
  23. return
  24. }
  25. if (*h)[len(*h)-1] != 8 {
  26. t.Error("Unexpected maximum:", (*h)[len(*h)-1])
  27. return
  28. }
  29. if res := h.Peek(); res != (*h)[0] {
  30. t.Error("Unexpected peek result:", res)
  31. return
  32. }
  33. var buf bytes.Buffer
  34. for h.Len() > 0 {
  35. buf.WriteString(fmt.Sprintf("%d ", heap.Pop(h)))
  36. }
  37. if buf.String() != "1 2 3 5 8 " {
  38. t.Error("Unexpected sort order:", buf.String())
  39. }
  40. buf.Reset()
  41. h = &IntHeap{2, 1, 5}
  42. heap.Init(h)
  43. heap.Push(h, 3)
  44. heap.Push(h, 3)
  45. heap.Push(h, 8)
  46. h.RemoveAll(3)
  47. for h.Len() > 0 {
  48. buf.WriteString(fmt.Sprintf("%d ", heap.Pop(h)))
  49. }
  50. if buf.String() != "1 2 5 8 " {
  51. t.Error("Unexpected sort order:", buf.String())
  52. }
  53. buf.Reset()
  54. h = &IntHeap{2, 1, 5}
  55. heap.Init(h)
  56. heap.Push(h, 3)
  57. heap.Push(h, 3)
  58. heap.Push(h, 8)
  59. h.RemoveFirst(3)
  60. for h.Len() > 0 {
  61. buf.WriteString(fmt.Sprintf("%d ", heap.Pop(h)))
  62. }
  63. if buf.String() != "1 2 3 5 8 " {
  64. t.Error("Unexpected sort order:", buf.String())
  65. }
  66. heap.Push(h, 3)
  67. heap.Push(h, 3)
  68. heap.Push(h, 8)
  69. h.RemoveFirst(3)
  70. h.RemoveFirst(3)
  71. h.RemoveFirst(8)
  72. if h.Len() != 0 {
  73. t.Error("Unexpected size:", h.Len())
  74. return
  75. }
  76. }