package main
import (
"fmt"
)
type Heap struct {
data []int
}
func (h *Heap) Insert(val int) {
h.data = append(h.data, val) // add new value at the end
h.heapifyUp(len(h.data) - 1) // fix heap from bottom up
}
func (h *Heap) heapifyUp(index int) {
for index > 0 {
parent := (index - 1) / 2
if h.data[parent] >= h.data[index] {
break // heap property satisfied
}
h.data[parent], h.data[index] = h.data[index], h.data[parent] // swap
index = parent // move up to parent
}
}
func (h *Heap) Print() {
for i, v := range h.data {
fmt.Printf("[%d]=%d ", i, v)
}
fmt.Println()
}
func main() {
h := &Heap{}
inputs := []int{10, 5, 3, 2, 4, 1}
for _, v := range inputs {
h.Insert(v)
}
h.Print()
}
h.data = append(h.data, val) // add new value at the end
append new element at the bottom of the heap
h.heapifyUp(len(h.data) - 1) // fix heap from bottom up
restore heap property by moving new element up if needed
parent := (index - 1) / 2
find parent index to compare with current node
if h.data[parent] >= h.data[index] { break }
stop if parent is bigger or equal, heap property holds
h.data[parent], h.data[index] = h.data[index], h.data[parent]
swap child with parent to fix heap order
move index up to continue checking heap property
[0]=10 [1]=5 [2]=3 [3]=2 [4]=4 [5]=1