heap.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 "container/heap"
  11. /*
  12. IntHeap is a classic heap with int values.
  13. */
  14. type IntHeap []int
  15. func (h IntHeap) Len() int { return len(h) }
  16. func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
  17. func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  18. /*
  19. Push adds an item to the heap.
  20. */
  21. func (h *IntHeap) Push(x interface{}) {
  22. *h = append(*h, x.(int))
  23. }
  24. /*
  25. Pop removes an item to the heap.
  26. */
  27. func (h *IntHeap) Pop() interface{} {
  28. old := *h
  29. n := len(old)
  30. x := old[n-1]
  31. *h = old[0 : n-1]
  32. return x
  33. }
  34. /*
  35. Peek returns the next item but does not remove it like Pop.
  36. */
  37. func (h *IntHeap) Peek() int {
  38. return (*h)[0]
  39. }
  40. /*
  41. RemoveFirst removes the first occurrences of item r from the IntHeap.
  42. */
  43. func (h *IntHeap) RemoveFirst(r int) {
  44. heapList := *h
  45. for i, item := range heapList {
  46. if item == r {
  47. if i+1 < len(heapList) {
  48. *h = append(heapList[:i], heapList[i+1:]...)
  49. heap.Fix(h, i)
  50. break
  51. } else {
  52. *h = heapList[:i]
  53. }
  54. }
  55. }
  56. }
  57. /*
  58. RemoveAll removes all occurrences of item r from the IntHeap.
  59. */
  60. func (h *IntHeap) RemoveAll(r int) {
  61. newHeap := &IntHeap{}
  62. for len(*h) > 0 {
  63. item := heap.Pop(h)
  64. if item != r {
  65. heap.Push(newHeap, item)
  66. }
  67. }
  68. (*h) = *newHeap
  69. }