// An IntHeap is a min-heap of ints.
typeIntHeap[]intfunc(hIntHeap)Len()int{returnlen(h)}func(hIntHeap)Less(i,jint)bool{returnh[i]<h[j]}func(hIntHeap)Swap(i,jint){h[i],h[j]=h[j],h[i]}func(h*IntHeap)Push(xinterface{}){// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h=append(*h,x.(int))}func(h*IntHeap)Pop()interface{}{old:=*hn:=len(old)x:=old[n-1]*h=old[0:n-1]returnx}
实现了该接口后,就可以利用 Init 函数初始化一个堆,利用 Push 插入和利用 Pop 删除。相关的函数原型如下
// This example inserts several ints into an IntHeap, checks the minimum,
// and removes them in order of priority.
funcExample_intHeap(){h:=&IntHeap{2,1,5}heap.Init(h)heap.Push(h,3)fmt.Printf("minimum: %d\n",(*h)[0])forh.Len()>0{fmt.Printf("%d ",heap.Pop(h))}// Output:
// minimum: 1
// 1 2 3 5
}
// This example demonstrates a priority queue built using the heap interface.
packageheap_testimport("container/heap""fmt")// An Item is something we manage in a priority queue.
typeItemstruct{valuestring// The value of the item; arbitrary.
priorityint// The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
indexint// The index of the item in the heap.
}// A PriorityQueue implements heap.Interface and holds Items.
typePriorityQueue[]*Itemfunc(pqPriorityQueue)Len()int{returnlen(pq)}func(pqPriorityQueue)Less(i,jint)bool{// We want Pop to give us the highest, not lowest, priority so we use greater than here.
returnpq[i].priority>pq[j].priority}func(pqPriorityQueue)Swap(i,jint){pq[i],pq[j]=pq[j],pq[i]pq[i].index=ipq[j].index=j}func(pq*PriorityQueue)Push(xinterface{}){n:=len(*pq)item:=x.(*Item)item.index=n*pq=append(*pq,item)}func(pq*PriorityQueue)Pop()interface{}{old:=*pqn:=len(old)item:=old[n-1]item.index=-1// for safety
*pq=old[0:n-1]returnitem}// update modifies the priority and value of an Item in the queue.
func(pq*PriorityQueue)update(item*Item,valuestring,priorityint){item.value=valueitem.priority=priorityheap.Fix(pq,item.index)}// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
funcExample_priorityQueue(){// Some items and their priorities.
items:=map[string]int{"banana":3,"apple":2,"pear":4,}// Create a priority queue, put the items in it, and
// establish the priority queue (heap) invariants.
pq:=make(PriorityQueue,len(items))i:=0forvalue,priority:=rangeitems{pq[i]=&Item{value:value,priority:priority,index:i,}i++}heap.Init(&pq)// Insert a new item and then modify its priority.
item:=&Item{value:"orange",priority:1,}heap.Push(&pq,item)pq.update(item,item.value,5)// Take the items out; they arrive in decreasing priority order.
forpq.Len()>0{item:=heap.Pop(&pq).(*Item)fmt.Printf("%.2d:%s ",item.priority,item.value)}// Output:
// 05:orange 04:pear 03:banana 02:apple
}