Repository navigation
Expand file tree
/
Copy pathcustom_heaps.go
More file actions
114 lines (81 loc) · 2.43 KB
/
Copy pathcustom_heaps.go
File metadata and controls
114 lines (81 loc) · 2.43 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
type CustomHeapItem struct {
Value int
content any
}
type CustomHeap []CustomHeapItem
func (h CustomHeap) Left(i int) int {
return 2*i + 1
}
func (h CustomHeap) Right(i int) int {
return 2*i + 2
}
func (h CustomHeap) Parent(i int) int {
return (i - 1) / 2 // la division d'entier tronque tjrs en go
}
func (h CustomHeap) Len() int {
return len(h)
}
func (h CustomHeap) Less(i CustomHeapItem, j CustomHeapItem) bool {
return i.Value < j.Value
}
// maintient la propriété de max heap
// i c'est l'indice tel que tous les subtrees de i sont des heaps valides
// donc on fait on sait que i c'est l'endroit où il y a un problème
func (h *CustomHeap) maxHeapify(i int) {
heap := *h
left := heap.Left(i)
right := heap.Right(i)
// on regarde les enfants de i, est-ce qu'ils sont bons ?
// si c'est le cas, on change rien !
largest := i
if left < h.Len() && h.Less(heap[i], heap[left]) {
// oups ! notre root est plus petit que notre membre à gauche.
// on va devoir le faire descendre
largest = left
}
if right < heap.Len() && heap.Less(heap[largest], heap[right]) {
largest = right
}
if largest != i {
// on swap le root avec le membre le plus grand
heap[i], heap[largest] = heap[largest], heap[i]
heap.maxHeapify(largest) // largest c'est la position de notre root qu'on vient de swapper
}
}
func (h *CustomHeap) buildMaxHeap() {
// on veut appeler max heapify à partir du bas sur chaque noeud
for i := (h.Len() - 2) / 2; i >= 0; i-- {
h.maxHeapify(i)
}
}
func (h *CustomHeap) heapMaximum() CustomHeapItem {
return (*h)[0]
}
func (h *CustomHeap) heapExtractMax() CustomHeapItem {
heap := *h
if heap.Len() == 0 {
panic("heap underflow")
}
max := heap.heapMaximum()
heap[0], heap[heap.Len()-1] = heap[heap.Len()-1], heap[0]
heap = heap[:heap.Len()-1]
heap.maxHeapify(0)
return max
}
func (h *CustomHeap) heapIncreaseKey(idx int, value int) {
heap := *h
heap[idx].Value = value
// tant que le parent est plus petit, on swap pour faire remonter la nouvelle clef
for idx > 0 && heap[heap.Parent(idx)].Value < heap[idx].Value {
heap[idx], heap[heap.Parent(idx)] = heap[heap.Parent(idx)], heap[idx]
idx = heap.Parent(idx)
}
}
func (h *CustomHeap) maxHeapInsert(item CustomHeapItem) {
heap := *h
heap = append(heap, item)
// à heap.Len() -1 on va avoir l'élément qu'on vient juste d'ajouter
// on trigger un nouveau calcul de sa position
heap.heapIncreaseKey(heap.Len()-1, item.Value)
}