參考文檔
謝謝這兩位博主,兩位博主寫的很好,我看了很久,自己總結的記錄如下。
堆 堆排序 優先隊列 圖文詳解(Golang實現)
最大堆,最小堆實現
堆
我們經常需要從一組對象中查找前N大值或小值。當然我們可以每次都先排序,然後再進行查找,但是這種做法效率很低。那麼有沒有一種特殊的數據結構,可以高效率的實現我們的需求呢,答案就是堆(heap)。Delete的複雜度爲O(1),Insert不大於樹的高度。
介紹
- 堆的最小值或最大值在根節點上,所以可以快速找到最大值或最小值。
- 堆是一棵完全二叉樹,所以我們可以用順序結構來存儲它,用一個數組表示,不需要指針,所以效率更高。
- 當用數組表示時,數組中任一位置i上的元素,其左兒子(如果存在)在位置2i上,右兒子(如果存在)在位置(2i + 1)上,其父節點在位置(i/2)上。
實現(Go)
我的目錄
堆實現代碼(我是小白,求指導)
package heap
import (
"fmt"
"math"
)
//二叉堆是一種特殊的堆,它滿足兩個性質:結構性和堆序性
//結構性:二叉堆是一顆完全二叉樹,完全二叉樹可以用一個數組表示,不需要指針,所以效率更高。
//堆序性質:堆的最小值或最大值在根節點上,所以可以快速找到最大值或最小值。
//當用數組表示時,數組中任一位置i上的元素,其左兒子在位置2i上,右兒子在位置(2i+ 1)上,其父節點在位置(i/2)上。
type Interface interface {
Len(heap *MaxHeap) int
swap(i, j int)
Bigger(i, j int) bool
Insert(value int)
Delete()
}
//Define MaxHeap
type MaxHeap struct {
Element []int
}
// New a Heap
func NewHeap() *MaxHeap {
//math.MinInt64 --> Integer limit values.
return &MaxHeap{Element: []int{math.MaxInt64}}
}
// Implementing Methods
func (heap *MaxHeap) Len(i, j int) int {
return len(heap.Element) - 1
}
func (heap *MaxHeap) Swap(i, j int) {
heap.Element[i], heap.Element[j] = heap.Element[j], heap.Element[i]
}
func (heap *MaxHeap) Bigger(i, j int) bool {
return heap.Element[i] > heap.Element[j]
}
func (heap *MaxHeap) Insert(value int) {
heap.Element = append(heap.Element, value)
i := len(heap.Element) - 1
//上浮
for ; heap.Bigger(i, i/2); i /= 2 {
heap.Swap(i, i/2)
}
}
func (heap *MaxHeap) Delete() {
if len(heap.Element) == 1 {
fmt.Println("empty heap")
return
}
heap.Element[1] = heap.Element[len(heap.Element)-1]
heap.Element = heap.Element[:len(heap.Element)-1]
i := 1
//Assuming
MaxPos := i
// If 2i and 2i + 1 exist , find MaxPos of (heap.Element[i], heap.Element[2i], heap.Element[2i+1])
// and swap(i, MaxPos)
for {
// Find MaxPos
if 2*i+1 <= len(heap.Element)-1 && heap.Bigger(2*i+1, i) {
MaxPos = 2*i + 1
}
if 2*i <= len(heap.Element)-1 && heap.Element[MaxPos] < heap.Element[2*i] {
MaxPos = 2 * i
}
//判斷是否進行交換
if MaxPos == i {
return
} else {
heap.Swap(i, MaxPos)
i = MaxPos
}
}
}
主函數(我是小白,求評論指導)
package main
import (
"fmt"
"github.com/iceriverdog/hellogo/Heap/heap"
)
func main() {
h := heap.NewHeap()
arr := []int{8, 1, 4, 5, 2}
for _, v := range arr {
h.Insert(v)
}
fmt.Println(h.Element)
h.Delete()
fmt.Println(h.Element)
h.Delete()
fmt.Println(h.Element)
h.Delete()
fmt.Println(h.Element)
h.Delete()
fmt.Println(h.Element)
h.Delete()
fmt.Println(h.Element)
}
希望大家評論指導我! 謝謝 !