package main
import (
"fmt"
)
type MinHeap struct {
arr []int
}
func (h *MinHeap) bubbleDown(index int) {
n := len(h.arr)
for {
left := 2*index + 1
right := 2*index + 2
smallest := index
if left < n && h.arr[left] < h.arr[smallest] {
smallest = left
}
if right < n && h.arr[right] < h.arr[smallest] {
smallest = right
}
if smallest == index {
break // heap property restored
}
h.arr[index], h.arr[smallest] = h.arr[smallest], h.arr[index]
index = smallest // continue bubbling down
}
}
func (h *MinHeap) ExtractMin() (int, bool) {
n := len(h.arr)
if n == 0 {
return 0, false // empty heap
}
min := h.arr[0]
h.arr[0] = h.arr[n-1] // move last to root
h.arr = h.arr[:n-1] // remove last
h.bubbleDown(0) // fix heap
return min, true
}
func main() {
h := MinHeap{arr: []int{1, 3, 5, 7, 9, 8}}
min, ok := h.ExtractMin()
if ok {
fmt.Printf("Extracted min: %d\n", min)
fmt.Printf("Heap after extract: %v\n", h.arr)
} else {
fmt.Println("Heap is empty")
}
}
h.arr[0] = h.arr[n-1] // move last to root
Replace root with last element to keep complete tree shape
h.arr = h.arr[:n-1] // remove last
Remove last element since it's moved to root
h.bubbleDown(0) // fix heap
Restore heap order by pushing down the new root
if left < n && h.arr[left] < h.arr[smallest] { smallest = left }
Find smaller child to swap with
if right < n && h.arr[right] < h.arr[smallest] { smallest = right }
Check right child for smaller value
if smallest == index { break }
Stop if heap property is restored
h.arr[index], h.arr[smallest] = h.arr[smallest], h.arr[index]
Swap current node with smaller child
index = smallest // continue bubbling down
Move down to child's position
Extracted min: 1
Heap after extract: [3 7 5 8 9]