File tree Expand file tree Collapse file tree 2 files changed +65
-7
lines changed Expand file tree Collapse file tree 2 files changed +65
-7
lines changed Original file line number Diff line number Diff line change 11package heap
22
3- import "fmt"
4-
53type Heap struct {
64a []int
75n int
@@ -49,23 +47,29 @@ func (heap *Heap) removeMax() {
4947swap (heap .a , 1 , heap .count )
5048heap .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
5559maxIndex := i
56- if heap . a [i ] < heap . a [i * 2 ] {
60+ if a [i ] < a [i * 2 ] {
5761maxIndex = 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 ] {
6165maxIndex = i * 2 + 1
6266}
6367
6468if maxIndex == i {
6569break
6670}
6771
68- swap (heap . a , i , maxIndex )
72+ swap (a , i , maxIndex )
6973i = maxIndex
7074}
7175
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments