package main
import (
"container/heap"
"fmt"
)
// IntHeap is a min-heap of ints
// Implements heap.Interface
// This is Go's standard heap usage
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{}) {
// Push appends element at the end
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
// Pop removes last element
n := len(*h)
x := (*h)[n-1]
*h = (*h)[:n-1]
return x
}
func main() {
// Sorted array simulation
sorted := []int{1, 3, 5, 7, 9, 0} // added extra space for insertion
// Remove min (first element) by shifting left
min := sorted[0]
for i := 1; i < len(sorted)-1; i++ {
sorted[i-1] = sorted[i] // shift left
}
sorted[len(sorted)-1] = 0 // clear last
// Insert 2 in sorted array by shifting right
val := 2
pos := len(sorted) - 2
for pos >= 0 && sorted[pos] > val {
sorted[pos+1] = sorted[pos] // shift right
pos--
}
sorted[pos+1] = val
// Print sorted array after operations
fmt.Print("Sorted array after remove min and insert 2: ")
for _, v := range sorted[:len(sorted)-1] {
if v != 0 {
fmt.Printf("%d -> ", v)
}
}
fmt.Println("null")
// Heap operations
h := &IntHeap{1, 3, 5, 7, 9}
heap.Init(h) // build heap
// Remove min (Pop)
minHeap := heap.Pop(h).(int)
// Insert 2 (Push)
heap.Push(h, 2)
// Print heap after operations
fmt.Print("Heap after remove min and insert 2: ")
for _, v := range *h {
fmt.Printf("%d -> ", v)
}
fmt.Println("null")
// Print removed mins
fmt.Printf("Removed min from sorted array: %d\n", min)
fmt.Printf("Removed min from heap: %d\n", minHeap)
}
for i := 1; i < len(sorted)-1; i++ {
sorted[i-1] = sorted[i] // shift left
}
shift elements left to remove first element in sorted array
for pos >= 0 && sorted[pos] > val {
sorted[pos+1] = sorted[pos] // shift right
pos--
}
shift elements right to insert new value in sorted array maintaining order
heap.Init(h) // build heap
build heap structure from initial array
minHeap := heap.Pop(h).(int)
remove min element from heap efficiently
insert new value into heap efficiently
Sorted array after remove min and insert 2: 2 -> 3 -> 5 -> 7 -> 9 -> null
Heap after remove min and insert 2: 2 -> 3 -> 5 -> 7 -> 9 -> null
Removed min from sorted array: 1
Removed min from heap: 1