github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/coding/container/01-heap.go (about)

     1  package main
     2  
     3  import (
     4  	"container/heap"
     5  	"fmt"
     6  )
     7  
     8  // 借助container/heap 接口 实现最小堆
     9  
    10  type IntHeap []int
    11  
    12  // 实现五个接口
    13  
    14  func (p IntHeap) Len() int {
    15  	return len(p)
    16  }
    17  
    18  func (p IntHeap) Less(i, j int) bool {
    19  	return p[i] < p[j]
    20  }
    21  
    22  func (p IntHeap) Swap(i, j int) {
    23  	p[i], p[j] = p[j], p[i]
    24  }
    25  
    26  func (p *IntHeap) Push(data interface{}) {
    27  	(*p) = append(*p, data.(int))
    28  }
    29  
    30  func (p *IntHeap) Pop() interface{} {
    31  	old := *p
    32  	n := len(old)
    33  	item := old[n-1]
    34  	*p = old[:n-1]
    35  	return item
    36  }
    37  
    38  func main() {
    39  	ih := &IntHeap{2, 1, 5}
    40  	heap.Init(ih)
    41  	heap.Push(ih, 3)
    42  	fmt.Printf("minimum: %d\n", (*ih)[0])
    43  	for ih.Len() > 0 {
    44  		fmt.Printf("%d ", heap.Pop(ih))
    45  	}
    46  }
    47  
    48  /*
    49  output
    50  minimum: 1
    51  1 2 3 5
    52  */