• 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. }

  • 相关阅读:
    一、TestNG的基本使用
    菜鸟学习第一天
    结合瑞幸的私域运营 盘点那些错误的私域营销方式
    Codeforces 353D 思维
    [附源码]计算机毕业设计JAVAjsp宾馆客房管理系统
    组件设计思想
    Linux-Ubuntu lxml库导入失败 解决方法
    vue前端中v-model与ref的区别
    【Linux】 find命令使用
    【Hack The Box】windows练习-- Bastard
  • 原文地址:https://blog.csdn.net/qq_32783703/article/details/126384632