Insert 5 Insert 3 Insert 8 Insert 1 Print queue
Remember, in a min-priority queue, the smallest element is always at the front.
After inserting 5, 3, 8, and 1, the min-priority queue orders elements so that the smallest is first. The queue becomes 1 -> 3 -> 5 -> 8 -> null.
Insert 10 Insert 20 Insert 15 Remove highest priority Print queue
In a max-priority queue, the largest element is removed first.
Initially, the queue is 20 -> 15 -> 10. Removing the highest priority (20) leaves 15 -> 10.
package main import ( "container/heap" "fmt" ) type IntHeap []int func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) } func (h *IntHeap) Pop() interface{} { n := len(*h) x := (*h)[n-1] *h = (*h)[:n-1] return x } func main() { h := &IntHeap{2, 1, 5} heap.Init(h) heap.Push(h, 3) fmt.Printf("min: %d\n", (*h)[0]) for i := 0; i < 4; i++ { fmt.Printf("%d ", heap.Pop(h)) } }
Check the loop condition when popping elements from the heap.
The loop runs from i = 0 to i = h.Len() inclusive, but h.Len() decreases with each pop. This causes an index out of range error.
Think about the shape and order properties of heaps.
A binary heap must be a complete binary tree and maintain the heap property where parents are ordered relative to children.
Each insertion takes O(log n) time. Consider n insertions.
Each insertion into a binary heap takes O(log n) time. Doing this n times results in O(n log n) total time.
