-
-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathheapsort.go
53 lines (41 loc) · 1.02 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
51
52
53
package HeapSort
type Heap struct{}
func (heap *Heap) HeapSort(array []int) []int {
heap.BuildHeap(array)
for length := len(array); length > 1; length-- {
heap.RemoveTop(array, length)
}
return array
}
// BuildHeap : Build heap from array
func (heap *Heap) BuildHeap(array []int) {
for i := len(array) / 2; i >= 0; i-- {
heap.Heapify(array, i, len(array))
}
}
func (heap *Heap) RemoveTop(array []int, length int) {
var lastIndex = length - 1
array[0], array[lastIndex] = array[lastIndex], array[0]
heap.Heapify(array, 0, lastIndex)
}
// Heapify : Heapify array
func (heap *Heap) Heapify(array []int, root, length int) {
var max = root
var l, r = heap.Left(root), heap.Right(root)
if l < length && array[l] > array[max] {
max = l
}
if r < length && array[r] > array[max] {
max = r
}
if max != root {
array[root], array[max] = array[max], array[root]
heap.Heapify(array, max, length)
}
}
func (*Heap) Left(root int) int {
return (root * 2) + 1
}
func (*Heap) Right(root int) int {
return (root * 2) + 2
}