duanhuang1967 2017-03-31 04:56
浏览 27
已采纳

Go的堆接口如何工作?

In Go, you can implement a heap as such: https://golang.org/src/container/heap/example_pq_test.go

You implement the sort.Interface, Pop, and Push and you've got yourself a priority queue/heap. In the example of both Pop and Push implementations the heap.Fix function isn't called. I see that heap.Init is called, so I can understand some heap-ifying happening then. However, you are able to push and pop items, which runs your own code, and the heap property is maintained.

If you push or pop items after init without calling heap.fix, how does the heap property get maintained?

Here's a playground of the example: https://play.golang.org/p/wE413xwmxE

  • 写回答

1条回答 默认 最新

  • duanchouyi6730 2017-03-31 07:24
    关注

    To keep heap implementation simple, you are only required to provide queuing logic for your custom type. Heapification is done by the heap package itself. It does so by calling the Push/Pop defined on your type, and then calling the heapification procedure:

    // from golang.org/src/container/heap/heap.go
    
    // Push pushes the element x onto the heap. The complexity is
    // O(log(n)) where n = h.Len().
    //
    func Push(h Interface, x interface{}) {
        h.Push(x)        // call to Push defined on your custom type
        up(h, h.Len()-1) // **heapification**
    }
    
    // Pop removes the minimum element (according to Less) from the heap
    // and returns it. The complexity is O(log(n)) where n = h.Len().
    // It is equivalent to Remove(h, 0).
    //
    func Pop(h Interface) interface{} {
        n := h.Len() - 1
        h.Swap(0, n)
        down(h, 0, n) // **heapification**
        return h.Pop()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算