// 用sort.IntSlice建堆,因为sort.IntSlice已经实现了Less, Swap, Len 方法
// hheap继承自sort.IntSlice
type hheap struct {
sort.IntSlice
}
// Less 根据需要重写Less, 变成大根堆
func (s hheap) Less(i, j int) bool {
if s.IntSlice[i] > s.IntSlice[j] {
return true
}
return false
}
func (s *hheap) Push(v interface{}) {
s.IntSlice = append(s.IntSlice, v.(int))
}
func (s *hheap) Pop() interface{} {
v := s.IntSlice[s.IntSlice.Len()-1]
s.IntSlice = s.IntSlice[:s.IntSlice.Len()-1]
return v
}
测试代码:
func main() {
heap1 := &hheap{sort.IntSlice{3, 6, 4, 1}}
heap.Init(heap1)
n := heap1.Len()
for i := 0; i < n; i++ {
fmt.Println(heap.Pop(heap1).(int))
}
}