go实现一个最小堆
参考视频:https://www.youtube.com/watch?v=JHeqKwr7F38.
package main
import "fmt"
type MinHeap struct {
array []int // 堆里面存放的节点
}
func parent(i int) int { // 根据当前下标找到父节点下标
return (i - 1) / 2
}
func left(i int) int { // 根据当前下标找左孩子下标
return i*2 + 1
}
func right(i int) int { // 根据当前下标找右孩子下标
return i*2 + 2
}
func (h *MinHeap) swap(first, second int) { // swap
h.array[first], h.array[second] = h.array[second], h.array[first]
}
func (h *MinHeap) insert(item int) { // insert
h.array = append(h.array, item) // 插入到最后一个
// Move node to correct position
h.HeapifyUp(len(h.array) - 1) // 最后一个值向上堆化
}
func (h *MinHeap) HeapifyUp(index int) { // 向上堆化
for h.array[parent(index)] > h.array[index] {
h.swap(parent(index), index)
// update index
index = parent(index)
}
}
func (h *MinHeap) remove() int { // remove
removed := h.array[0]
l := len(h.array) - 1
if len(h.array) == 0 {
return -1
}
// Move that last node to the beginning
h.array[0] = h.array[l]
// Slice off the last position since there
// is one less node in the queue
h.array = h.array[:l]
h.HeapifyDown(0) // 向下堆化
return removed
}
func (h *MinHeap) HeapifyDown(index int) {
lastIndexToCheck := len(h.array) - 1
l, r := left(index), right(index)
childToCompare := 0
// find the smallest of the lft and right children
for l <= lastIndexToCheck {
if l == lastIndexToCheck {
childToCompare = l
} else if h.array[l] < h.array[r] {
childToCompare = l
} else {
childToCompare = r
}
// swap the parent with the smallest
if h.array[index] > h.array[childToCompare] {
h.swap(index, childToCompare)
// Update the indices that we are comparing
index = childToCompare
l, r = left(index), right(index)
} else {
return
}
}
}
func main() {
mh := &MinHeap{}
mh.insert(35)
mh.insert(11)
mh.insert(23)
mh.insert(25)
mh.insert(17)
mh.insert(19)
mh.insert(30)
mh.insert(15)
mh.insert(8)
mh.insert(22)
fmt.Println(mh.array)
a := mh.remove() // Remove 8
fmt.Printf("\nRemoved %d\n", a)
fmt.Println(mh.array)
mh.insert(6)
fmt.Println("\ninserted 6")
fmt.Println(mh.array)
}
// output
[8 11 19 15 22 23 30 35 17 25]
Removed 8
[11 15 19 17 22 23 30 35 25]
inserted 6
[6 11 19 17 15 23 30 35 25 22]
谢谢观看