• golang实现一个优先队列


    1. package main
    2. import "fmt"
    3. type StreamPriorityQueueData struct {
    4. key int
    5. value int
    6. }
    7. type StreamPriorityQueue struct {
    8. caches []StreamPriorityQueueData
    9. size int
    10. capacity int
    11. }
    12. func NewStreamPriorityQueue(size int) *StreamPriorityQueue {
    13. return &StreamPriorityQueue{
    14. caches: make([]StreamPriorityQueueData, size),
    15. capacity: size,
    16. }
    17. }
    18. func (q *StreamPriorityQueue) GetQueueTop() StreamPriorityQueueData {
    19. if len(q.caches) == 0 {
    20. return StreamPriorityQueueData{}
    21. }
    22. return q.caches[0]
    23. }
    24. func (q *StreamPriorityQueue) EnQueue(data StreamPriorityQueueData) {
    25. if q.size == q.capacity {
    26. return
    27. }
    28. q.size++
    29. var i int
    30. for i = q.size; q.caches[i/2].key > data.key; i /= 2 {
    31. q.caches[i] = q.caches[i/2]
    32. }
    33. q.caches[i] = data
    34. }
    35. func (q *StreamPriorityQueue) DeQueue() StreamPriorityQueueData {
    36. if q.size == 0 {
    37. return q.caches[0]
    38. }
    39. minElements := q.caches[1]
    40. lastElements := q.caches[(q.size)]
    41. var i int
    42. var child int
    43. for i = 1; i*2 <= q.size; i = child {
    44. child = i * 2
    45. //左右子节点比较,选较小的一方
    46. if child != q.size && (q.caches[child+1].key < q.caches[child].key) {
    47. child++
    48. }
    49. //最后一个元素和子节点比较,如果最后一个元素大,上提子节点
    50. if lastElements.key > q.caches[child].key {
    51. q.caches[i] = q.caches[child]
    52. } else {
    53. break
    54. }
    55. }
    56. q.caches[i] = lastElements
    57. fmt.Println(minElements)
    58. return minElements
    59. }
    60. func main() {
    61. q := NewStreamPriorityQueue(8)
    62. d := StreamPriorityQueueData{
    63. key: 1,
    64. value: 1,
    65. }
    66. q.EnQueue(d)
    67. d1 := StreamPriorityQueueData{
    68. key: 2,
    69. value: 2,
    70. }
    71. q.EnQueue(d1)
    72. d2 := StreamPriorityQueueData{
    73. key: 3,
    74. value: 3,
    75. }
    76. q.EnQueue(d2)
    77. d3 := StreamPriorityQueueData{
    78. key: 4,
    79. value: 4,
    80. }
    81. q.EnQueue(d3)
    82. d4 := StreamPriorityQueueData{
    83. key: 5,
    84. value: 5,
    85. }
    86. q.EnQueue(d4)
    87. q.DeQueue()
    88. q.DeQueue()
    89. q.DeQueue()
    90. q.DeQueue()
    91. q.DeQueue()
    92. q.EnQueue(d3)
    93. q.DeQueue()
    94. }

  • 相关阅读:
    el-dialog el-select适配移动端
    C++设计模式之代理模式(结构型模式)
    Android使用Coordinatorlayout以及自定义Behavior实现滑动折叠效果
    公众号留言功能报价是多少?值得开通吗?
    多功能投票系统(ThinkPHP+FastAdmin+Uniapp)
    面向对象方法学:对象
    Map接口
    Apache Commons IO组件简介说明
    Dubbo环境搭建
    Flink SQL --命令行的使用(02)
  • 原文地址:https://blog.csdn.net/qq_32783703/article/details/126384632