Skip to content

Commit 086276d

Browse files
committed
add heap algo
1 parent 63c27a9 commit 086276d

File tree

2 files changed

+65
-7
lines changed

2 files changed

+65
-7
lines changed

go/28_heap/heap.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package heap
22

3-
import "fmt"
4-
53
type Heap struct {
64
a []int
75
n int
@@ -49,23 +47,29 @@ func (heap *Heap) removeMax() {
4947
swap(heap.a, 1, heap.count)
5048
heap.count--
5149

52-
//comapre with left and right
53-
for i := 1; i <= heap.count/2; {
50+
//heapify from up to down
51+
heapifyUpToDown(heap.a, heap.count)
52+
}
53+
54+
//heapify
55+
func heapifyUpToDown(a []int, count int) {
56+
57+
for i := 1; i <= count/2; {
5458

5559
maxIndex := i
56-
if heap.a[i] < heap.a[i*2] {
60+
if a[i] < a[i*2] {
5761
maxIndex = i * 2
5862
}
5963

60-
if i*2+1 <= heap.count && heap.a[maxIndex] < heap.a[i*2+1] {
64+
if i*2+1 <= count && a[maxIndex] < a[i*2+1] {
6165
maxIndex = i*2 + 1
6266
}
6367

6468
if maxIndex == i {
6569
break
6670
}
6771

68-
swap(heap.a, i, maxIndex)
72+
swap(a, i, maxIndex)
6973
i = maxIndex
7074
}
7175

go/28_heap/heap_sort.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package heap
2+
3+
//build a heap
4+
func buidHeap(a []int, n int) {
5+
6+
//heapify from the last parent node
7+
for i := n / 2; i >= 1; i-- {
8+
heapifyUpToDown(a, i, n)
9+
}
10+
11+
}
12+
13+
//sort by ascend, a index begin from 1, has n elements
14+
func sort(a []int, n int) {
15+
buidHeap(a, n)
16+
17+
k := n
18+
for k >= 1 {
19+
swap(a, 1, k)
20+
heapifyUpToDown(a, 1, k-1)
21+
k--
22+
}
23+
}
24+
25+
//heapify from up to down , node index = top
26+
func heapifyUpToDown(a []int, top int, count int) {
27+
28+
for i := top; i <= count/2; {
29+
30+
maxIndex := i
31+
if a[i] < a[i*2] {
32+
maxIndex = i * 2
33+
}
34+
35+
if i*2+1 <= count && a[maxIndex] < a[i*2+1] {
36+
maxIndex = i*2 + 1
37+
}
38+
39+
if maxIndex == i {
40+
break
41+
}
42+
43+
swap(a, i, maxIndex)
44+
i = maxIndex
45+
}
46+
47+
}
48+
49+
//swap two elements
50+
func swap(a []int, i int, j int) {
51+
tmp := a[i]
52+
a[i] = a[j]
53+
a[j] = tmp
54+
}

0 commit comments

Comments
 (0)