File tree Expand file tree Collapse file tree 2 files changed +137
-0
lines changed
Expand file tree Collapse file tree 2 files changed +137
-0
lines changed Original file line number Diff line number Diff line change 1+ package heap
2+
3+ type Heap struct {
4+ a []int
5+ n int
6+ count int
7+ }
8+
9+ //init heap
10+ func NewHeap (capacity int ) * Heap {
11+ heap := & Heap {}
12+ heap .n = capacity
13+ heap .a = make ([]int , capacity + 1 )
14+ heap .count = 0
15+ return heap
16+ }
17+
18+ //top-max heap -> heapify from down to up
19+ func (heap * Heap ) insert (data int ) {
20+ //defensive
21+ if heap .count == heap .n {
22+ return
23+ }
24+
25+ heap .count ++
26+ heap .a [heap .count ] = data
27+
28+ //compare with parent node
29+ i := heap .count
30+ parent := i / 2
31+ for parent > 0 && heap .a [parent ] < heap .a [i ] {
32+ swap (heap .a , parent , i )
33+ i = parent
34+ parent = i / 2
35+ }
36+ }
37+
38+ //heapfify from up to down
39+ func (heap * Heap ) removeMax () {
40+
41+ //defensive
42+ if heap .count == 0 {
43+ return
44+ }
45+
46+ //swap max and last
47+ swap (heap .a , 1 , heap .count )
48+ heap .count --
49+
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 ; {
58+
59+ maxIndex := i
60+ if a [i ] < a [i * 2 ] {
61+ maxIndex = i * 2
62+ }
63+
64+ if i * 2 + 1 <= count && a [maxIndex ] < a [i * 2 + 1 ] {
65+ maxIndex = i * 2 + 1
66+ }
67+
68+ if maxIndex == i {
69+ break
70+ }
71+
72+ swap (a , i , maxIndex )
73+ i = maxIndex
74+ }
75+
76+ }
77+
78+ //swap two elements
79+ func swap (a []int , i int , j int ) {
80+ tmp := a [i ]
81+ a [i ] = a [j ]
82+ a [j ] = tmp
83+ }
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