min_heap.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package dispatch
  2. import (
  3. "container/heap"
  4. "errors"
  5. )
  6. type HeapData []*HeapDataItem
  7. type HeapDataItem struct {
  8. value interface{}
  9. weight float64
  10. }
  11. func (d HeapData) Len() int {
  12. return len(d)
  13. }
  14. func (d HeapData) Swap(i, j int) {
  15. d[i], d[j] = d[j], d[i]
  16. }
  17. func (d *HeapData) Push(x interface{}) {
  18. item := x.(*HeapDataItem)
  19. *d = append(*d, item)
  20. }
  21. func (d *HeapData) Pop() interface{} {
  22. old := *d
  23. n := len(old)
  24. item := old[n-1]
  25. *d = old[0 : n-1]
  26. return item
  27. }
  28. type MinHeapData struct {
  29. HeapData
  30. }
  31. func (d MinHeapData) Less(i, j int) bool {
  32. return d.HeapData[i].weight < d.HeapData[j].weight
  33. }
  34. type MinHeap struct {
  35. data MinHeapData
  36. }
  37. func NewMinHeap() *MinHeap {
  38. h := new(MinHeap)
  39. heap.Init(&h.data)
  40. return h
  41. }
  42. func (h *MinHeap) HeapPush(value interface{}, weight float64) {
  43. heap.Push(&h.data, &HeapDataItem{
  44. value: value,
  45. weight: weight,
  46. })
  47. }
  48. func (h *MinHeap) HeapPop() (interface{}, float64, error) {
  49. if h.data.Len() == 0 {
  50. return nil, 0, errors.New("heap is empty")
  51. }
  52. item := heap.Pop(&h.data).(*HeapDataItem)
  53. return item.value, item.weight, nil
  54. }
  55. func (h *MinHeap) HeapTop() (interface{}, float64, error) {
  56. if h.data.Len() == 0 {
  57. return nil, 0, errors.New("heap is empty")
  58. }
  59. item := h.data.HeapData[0]
  60. return item.value, item.weight, nil
  61. }
  62. func (h *MinHeap) HeapLength() int {
  63. return h.data.Len()
  64. }