forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheapsort.go
50 lines (43 loc) · 1.07 KB
/
heapsort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package sort
type maxHeap struct {
slice []int
heapSize int
}
func buildMaxHeap(slice []int) maxHeap {
h := maxHeap{slice: slice, heapSize: len(slice)}
for i := len(slice) / 2; i >= 0; i-- {
h.MaxHeapify(i)
}
return h
}
func (h maxHeap) MaxHeapify(i int) {
l, r := 2*i+1, 2*i+2
max := i
if l < h.size() && h.slice[l] > h.slice[max] {
max = l
}
if r < h.size() && h.slice[r] > h.slice[max] {
max = r
}
//log.Printf("MaxHeapify(%v): l,r=%v,%v; max=%v\t%v\n", i, l, r, max, h.slice)
if max != i {
h.slice[i], h.slice[max] = h.slice[max], h.slice[i]
h.MaxHeapify(max)
}
}
func (h maxHeap) size() int { return h.heapSize } // ???
func HeapSort(slice []int) []int {
h := buildMaxHeap(slice)
//log.Println(slice)
for i := len(h.slice) - 1; i >= 1; i-- {
h.slice[0], h.slice[i] = h.slice[i], h.slice[0]
h.heapSize--
h.MaxHeapify(0)
/*if i == len(h.slice)-1 || i == len(h.slice)-3 || i == len(h.slice)-5 {
element := (i - len(h.slice)) * -1
fmt.Println("Heap after removing ", element, " elements")
fmt.Println(h.slice)
}*/
}
return h.slice
}