Skip to content

Commit 63c27a9

Browse files
committed
add heap insert and delete in golang
1 parent dbe8801 commit 63c27a9

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

go/28_heap/heap.go

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package heap
2+
3+
import "fmt"
4+
5+
type Heap struct {
6+
a []int
7+
n int
8+
count int
9+
}
10+
11+
//init heap
12+
func NewHeap(capacity int) *Heap {
13+
heap := &Heap{}
14+
heap.n = capacity
15+
heap.a = make([]int, capacity+1)
16+
heap.count = 0
17+
return heap
18+
}
19+
20+
//top-max heap -> heapify from down to up
21+
func (heap *Heap) insert(data int) {
22+
//defensive
23+
if heap.count == heap.n {
24+
return
25+
}
26+
27+
heap.count++
28+
heap.a[heap.count] = data
29+
30+
//compare with parent node
31+
i := heap.count
32+
parent := i / 2
33+
for parent > 0 && heap.a[parent] < heap.a[i] {
34+
swap(heap.a, parent, i)
35+
i = parent
36+
parent = i / 2
37+
}
38+
}
39+
40+
//heapfify from up to down
41+
func (heap *Heap) removeMax() {
42+
43+
//defensive
44+
if heap.count == 0 {
45+
return
46+
}
47+
48+
//swap max and last
49+
swap(heap.a, 1, heap.count)
50+
heap.count--
51+
52+
//comapre with left and right
53+
for i := 1; i <= heap.count/2; {
54+
55+
maxIndex := i
56+
if heap.a[i] < heap.a[i*2] {
57+
maxIndex = i * 2
58+
}
59+
60+
if i*2+1 <= heap.count && heap.a[maxIndex] < heap.a[i*2+1] {
61+
maxIndex = i*2 + 1
62+
}
63+
64+
if maxIndex == i {
65+
break
66+
}
67+
68+
swap(heap.a, i, maxIndex)
69+
i = maxIndex
70+
}
71+
72+
}
73+
74+
//swap two elements
75+
func swap(a []int, i int, j int) {
76+
tmp := a[i]
77+
a[i] = a[j]
78+
a[j] = tmp
79+
}

0 commit comments

Comments
 (0)