golang 最小堆

package main

import (
    "container/heap"
    "fmt"
)

type IntHeap []int

func (h IntHeap) Len() int {
    return len(h)
}

func (h IntHeap) Less(i, j int) bool {
    return h[i] < h[j]
}

func (h IntHeap) Swap(i, j int) {
    h[i],h[j] = h[j],h[i]
}

func (h *IntHeap) Push(x interface{}) {
    *h = append(*h,x.(int))
}

func (h *IntHeap) Pop() interface{} {
    length := len(*h)
    last := (*h)[length-1]
    *h = (*h)[0:length-1]
    return last
}
func main()  {
    h := &IntHeap{3,8,5,2,4}
    heap.Init(h)
    heap.Push(h,7)
    for h.Len() > 0{
        fmt.Printf("%d\n",heap.Pop(h))
    }
    //2,3,4,5,7,8
}

你可能感兴趣的:(golang 最小堆)