can anyone explain me this thing: I want implement priority queue in GO (interface implementation got from link, but for lowest)
My code:
pq := make(PriorityQueue, 0)
pq.Push(&Item{value: 0, priority: 0})
heap.Init(&pq)
fmt.Println(heap.Pop(&pq).(*Item))
item := &Item{value: 1, priority: 10}
pq.Push(item)
item = &Item{value: 2, priority: 20}
pq.Push(item)
item = &Item{value: 3, priority: 5}
pq.Push(item)
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
// Output:
&{0 0 -1}
&{1 10 -1}
&{3 5 -1}
&{2 20 -1}
Why it not outputs:
&{0 0 -1}
&{3 5 -1}
...
The way this particular priority queue is implemented, you should call heap.Init
after you've pushed your items into the queue, as the original example demonstrates.
pq := make(PriorityQueue, 0)
pq.Push(&Item{value: "0", priority: 0, index: 0})
item := &Item{value: "1", priority: 10, index: 1}
pq.Push(item)
item = &Item{value: "2", priority: 20, index: 2}
pq.Push(item)
item = &Item{value: "3", priority: 5, index: 3}
pq.Push(item)
heap.Init(&pq)
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
fmt.Println(heap.Pop(&pq).(*Item))
Will print the items in priority order, as expected.
First note that you said you expected the lowest priority first, but the highest the number is, the highest the priority is. So it should be 20, 10, 5, 0.
In the docs:
Take the items out; they arrive in decreasing priority order.
I just took your data and put it into the example in the doc page (the link you provided). Check it out: play.golang.org/p/7GyYgJ-HAwi
The main difference is the heap.Init(&pq)
location.
Edit: @Eli Bendersky provided the answer while I was typing mine.