package main
import (
"container/heap"
"fmt"
)
// An IntHeap is a min-heap of ints.
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MinHeap) Pop() interface{} {
n := len(*h)
x := (*h)[n-1]
*h = (*h)[:n-1]
return x
}
// MaxHeap is a max-heap of ints.
type MaxHeap []int
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MaxHeap) Pop() interface{} {
n := len(*h)
x := (*h)[n-1]
*h = (*h)[:n-1]
return x
}
func main() {
minH := &MinHeap{}
heap.Init(minH)
for _, v := range []int{5, 3, 9, 1, 7} {
heap.Push(minH, v) // insert and bubble up
}
fmt.Print("Min Heap final: ")
for _, v := range *minH {
fmt.Printf("%d -> ", v)
}
fmt.Println("null")
maxH := &MaxHeap{}
heap.Init(maxH)
for _, v := range []int{1, 3, 5, 7, 9} {
heap.Push(maxH, v) // insert and bubble up
}
fmt.Print("Max Heap final: ")
for _, v := range *maxH {
fmt.Printf("%d -> ", v)
}
fmt.Println("null")
}
heap.Push(minH, v) // insert and bubble up
insert element and bubble up to maintain min heap property
heap.Push(maxH, v) // insert and bubble up
insert element and bubble up to maintain max heap property
Min Heap final: 1 -> 3 -> 9 -> 5 -> 7 -> null
Max Heap final: 9 -> 7 -> 5 -> 1 -> 3 -> null