Skip to content

Commit d7d3c2a

Browse files
committed
add heapsort in golang
1 parent 0cc3c84 commit d7d3c2a

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Sorting/HeapSort/go/HeapSort.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
a := []int{5, 109, 87, 4, 50, 908, 65, 22, 1, 36}
9+
a = heapsort(a)
10+
fmt.Println(a)
11+
}
12+
13+
func heapsort(a []int) []int {
14+
heapify(a, len(a))
15+
end := len(a) - 1
16+
for end > 0 {
17+
a[end], a[0] = a[0], a[end]
18+
end--
19+
traverse(a, 0, end)
20+
}
21+
return a
22+
}
23+
24+
func heapify(a []int, count int) {
25+
start := int((count - 2) / 2)
26+
for start >= 0 {
27+
traverse(a, start, count-1)
28+
start--
29+
}
30+
31+
}
32+
33+
func traverse(a []int, start, end int) {
34+
root := start
35+
for (root*2 + 1) <= end {
36+
child := root*2 + 1
37+
swap := root
38+
if a[swap] < a[child] {
39+
swap = child
40+
}
41+
if (child+1) <= end && a[swap] < a[child+1] {
42+
swap = child + 1
43+
}
44+
if swap != root {
45+
a[root], a[swap] = a[swap], a[root]
46+
root = swap
47+
} else {
48+
return
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)