0%

堆的实现

堆结构

  • 定义
    • 一种特殊形式的完全二叉树
    • 任何一个非终结节点的元素都不小(大)于其左右儿子节点的元素,则称此二叉树为最大(小)堆。

堆结构的基本操作

  1. MaxHeap() 申请一个空堆
  2. Insert() 向堆中插入元素
  3. HeapEmpty() 是否堆空
  4. DeletMax() 删除最大元素

插入操作

  • 插入到最后,然后和父节点比较,如果比父节点大,那么和父节点交换位置

删除操作

  • 将堆的末尾元素替换堆顶元素,然后将子节点,父节点中较大的元素作为父节点这样一直迭代下去。

堆结构的 golang 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package max_heap

import "fmt"

type MaxHeap struct {
Elements []int
Cnt int
}

func NewMaxHeap() *MaxHeap {
return &MaxHeap {Elements: []int{}, Cnt: -1}
}

func GenMaxHeap(elements []int) *MaxHeap {
maxHeap := NewMaxHeap()
for i:= 0; i < len(elements); i++ {
maxHeap.Insert(elements[i])
}
return maxHeap
}

func (maxHeap MaxHeap) PrintElements() {
for i := 0; i <= maxHeap.Cnt; i++ {
fmt.Print(maxHeap.Elements[i], " ")
}
}

func (maxHeap MaxHeap) HeapEmpty() bool {
return maxHeap.Cnt == -1
}

func (maxHeap *MaxHeap) Insert(element int) {
maxHeap.Cnt += 1
maxHeap.Elements = append(maxHeap.Elements, element)
var i = maxHeap.Cnt
for i != 0 && maxHeap.Elements[i] > maxHeap.Elements[(i+1) / 2 - 1] {
maxHeap.Elements[i], maxHeap.Elements[(i+1) / 2 - 1] =
maxHeap.Elements[(i + 1) / 2 - 1], maxHeap.Elements[i]
i = (i + 1) / 2 - 1
}
}

func (maxHeap *MaxHeap) DeleteMax() int {
tmp := maxHeap.Elements[0]
maxHeap.Elements[0] = maxHeap.Elements[maxHeap.Cnt]
maxHeap.Elements = maxHeap.Elements[0:maxHeap.Cnt]
maxHeap.Cnt -= 1
parentIdx := 0
for parentIdx <= maxHeap.Cnt {
leftchildIdx := (parentIdx + 1) * 2 - 1
if leftchildIdx > maxHeap.Cnt {
break
}
maxChildIdx := leftchildIdx
rightChildIdx := leftchildIdx + 1
if rightChildIdx <= maxHeap.Cnt && maxHeap.Elements[rightChildIdx] > maxHeap.Elements[leftchildIdx] {
maxChildIdx = rightChildIdx
}
if maxHeap.Elements[parentIdx] < maxHeap.Elements[maxChildIdx] {
maxHeap.Elements[parentIdx], maxHeap.Elements[maxChildIdx] =
maxHeap.Elements[maxChildIdx], maxHeap.Elements[parentIdx]

parentIdx = maxChildIdx
} else {
break
}
}
return tmp
}

func main() {
var num int
fmt.Scanf("%d", &num)
var heapArr []int
for i:= 0; i < num; i++ {
var tmp int
fmt.Scanf("%d", &tmp)
heapArr = append(heapArr, tmp)
}
maxHeap := GenMaxHeap(heapArr)
maxHeap.DeleteMax()
maxHeap.PrintElements()
}