Skip to content

Commit e5c87a7

Browse files
authored
Merge pull request tulika-99#55 from DGKSK8LIFE/master
Create HeapSort.go
2 parents 4ab0275 + b19f500 commit e5c87a7

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Heap Sort/HeapSort.go

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type MaxHeap struct {
6+
slice []int
7+
heapSize int
8+
}
9+
10+
func BuildMaxHeap(slice []int) MaxHeap {
11+
h := MaxHeap{slice: slice, heapSize: len(slice)}
12+
for i := len(slice) / 2; i >= 0; i-- {
13+
h.MaxHeapify(i)
14+
}
15+
return h
16+
}
17+
18+
func (h MaxHeap) MaxHeapify(i int) {
19+
l, r := 2*i+1, 2*i+2
20+
max := i
21+
22+
if l < h.size() && h.slice[l] > h.slice[max] {
23+
max = l
24+
}
25+
if r < h.size() && h.slice[r] > h.slice[max] {
26+
max = r
27+
}
28+
//log.Printf("MaxHeapify(%v): l,r=%v,%v; max=%v\t%v\n", i, l, r, max, h.slice)
29+
if max != i {
30+
h.slice[i], h.slice[max] = h.slice[max], h.slice[i]
31+
h.MaxHeapify(max)
32+
}
33+
}
34+
35+
func (h MaxHeap) size() int { return h.heapSize } // ???
36+
37+
func heapSort(slice []int) []int {
38+
h := BuildMaxHeap(slice)
39+
//log.Println(slice)
40+
for i := len(h.slice) - 1; i >= 1; i-- {
41+
h.slice[0], h.slice[i] = h.slice[i], h.slice[0]
42+
h.heapSize--
43+
h.MaxHeapify(0)
44+
}
45+
return h.slice
46+
}
47+
48+
func main() {
49+
s := []int{4, 1, 3, 2, 16, 9, 10, 14, 8, 7}
50+
h := BuildMaxHeap(s)
51+
fmt.Println(h)
52+
53+
s = heapSort(s)
54+
fmt.Println(s)
55+
}

0 commit comments

Comments
 (0)