Skip to content

Commit b185489

Browse files
Adding Heap-sort implemented in Go
1 parent a3f3e80 commit b185489

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

HeapSort/Go/heap-sort.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"time"
7+
)
8+
9+
func main() {
10+
var heap *Heap
11+
slice := generateSlice(20)
12+
fmt.Println("\n--- Unsorted --- \n\n", slice)
13+
heap.HeapSort(slice)
14+
fmt.Println("\n--- Sorted ---\n\n", slice)
15+
}
16+
17+
// Generates a slice of size, size filled with random numbers
18+
func generateSlice(size int) []int {
19+
20+
slice := make([]int, size, size)
21+
rand.Seed(time.Now().UnixNano())
22+
for i := 0; i < size; i++ {
23+
slice[i] = rand.Intn(999) - rand.Intn(999)
24+
}
25+
return slice
26+
}
27+
28+
type Heap struct {
29+
}
30+
31+
func (heap *Heap) HeapSort(array []int) {
32+
heap.BuildHeap(array)
33+
34+
for length := len(array); length > 1; length-- {
35+
heap.RemoveTop(array, length)
36+
}
37+
}
38+
39+
func (heap *Heap) BuildHeap(array []int) {
40+
for i := len(array) / 2; i >= 0; i-- {
41+
heap.Heapify(array, i, len(array))
42+
}
43+
}
44+
45+
func (heap *Heap) RemoveTop(array []int, length int) {
46+
var lastIndex = length - 1
47+
array[0], array[lastIndex] = array[lastIndex], array[0]
48+
heap.Heapify(array, 0, lastIndex)
49+
}
50+
51+
func (heap *Heap) Heapify(array []int, root, length int) {
52+
var max = root
53+
var l, r = heap.Left(array, root), heap.Right(array, root)
54+
55+
if l < length && array[l] > array[max] {
56+
max = l
57+
}
58+
59+
if r < length && array[r] > array[max] {
60+
max = r
61+
}
62+
63+
if max != root {
64+
array[root], array[max] = array[max], array[root]
65+
heap.Heapify(array, max, length)
66+
}
67+
}
68+
69+
func (*Heap) Left(array []int, root int) int {
70+
return (root * 2) + 1
71+
}
72+
73+
func (*Heap) Right(array []int, root int) int {
74+
return (root * 2) + 2
75+
}

0 commit comments

Comments
 (0)