Commit b2d1a2b5 authored by Robert Griesemer's avatar Robert Griesemer

container/heap: update example code

- use Init to establish heap invariant on
  a non-empty heap
- use Fix to update heap after an element's
  properties have been changed

(The old code used Init where it wasn't needed,
 and didn't use Fix because Fix was added after
 the example was written.)

LGTM=bradfitz
R=adonovan, bradfitz
CC=golang-codereviews
https://golang.org/cl/94520043
parent 7ad60b72
...@@ -52,13 +52,12 @@ func (pq *PriorityQueue) Pop() interface{} { ...@@ -52,13 +52,12 @@ func (pq *PriorityQueue) Pop() interface{} {
// update modifies the priority and value of an Item in the queue. // update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) { func (pq *PriorityQueue) update(item *Item, value string, priority int) {
heap.Remove(pq, item.index)
item.value = value item.value = value
item.priority = priority item.priority = priority
heap.Push(pq, item) heap.Fix(pq, item.index)
} }
// This example inserts some items into a PriorityQueue, manipulates an item, // This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order. // and then removes the items in priority order.
func Example_priorityQueue() { func Example_priorityQueue() {
// Some items and their priorities. // Some items and their priorities.
...@@ -66,28 +65,31 @@ func Example_priorityQueue() { ...@@ -66,28 +65,31 @@ func Example_priorityQueue() {
"banana": 3, "apple": 2, "pear": 4, "banana": 3, "apple": 2, "pear": 4,
} }
// Create a priority queue and put the items in it. // Create a priority queue, put the items in it, and
pq := &PriorityQueue{} // establish the priority queue (heap) invariants.
heap.Init(pq) pq := make(PriorityQueue, len(items))
i := 0
for value, priority := range items { for value, priority := range items {
item := &Item{ pq[i] = &Item{
value: value, value: value,
priority: priority, priority: priority,
index: i,
} }
heap.Push(pq, item) i++
} }
heap.Init(&pq)
// Insert a new item and then modify its priority. // Insert a new item and then modify its priority.
item := &Item{ item := &Item{
value: "orange", value: "orange",
priority: 1, priority: 1,
} }
heap.Push(pq, item) heap.Push(&pq, item)
pq.update(item, item.value, 5) pq.update(item, item.value, 5)
// Take the items out; they arrive in decreasing priority order. // Take the items out; they arrive in decreasing priority order.
for pq.Len() > 0 { for pq.Len() > 0 {
item := heap.Pop(pq).(*Item) item := heap.Pop(&pq).(*Item)
fmt.Printf("%.2d:%s ", item.priority, item.value) fmt.Printf("%.2d:%s ", item.priority, item.value)
} }
// Output: // Output:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment