从0开始实现一个最小堆|Golang

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]

谢谢观看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值