10000 Added Heap sort (#17) · SelfCodeLearning/Go@20bdcfd · GitHub
[go: up one dir, main page]

Skip to content

Commit 20bdcfd

Browse files
DanGarcia595dynamitechetan
authored andcommitted
Added Heap sort (TheAlgorithms#17)
* init Radix * init HeapSort
1 parent 02bdb71 commit 20bdcfd

File tree

2 files changed

+72
-81
lines changed

2 files changed

+72
-81
lines changed

sorts/Heapsort.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package main
2+
3+
import "fmt"
4+
import "math/rand"
5+
import "time"
6+
7+
type MaxHeap struct {
8+
slice []int
9+
heapSize int
10+
}
11+
12+
func BuildMaxHeap(slice []int) MaxHeap {
13+
h := MaxHeap{slice: slice, heapSize: len(slice)}
14+
for i := len(slice) / 2; i >= 0; i-- {
15+
h.MaxHeapify(i)
16+
}
17+
return h
18+
}
19+
20+
func (h MaxHeap) MaxHeapify(i int) {
21+
l, r := 2*i+1, 2*i+2
22+
max := i
23+
24+
if l < h.size() && h.slice[l] > h.slice[max] {
25+
max = l
26+
}
27+
if r < h.size() && h.slice[r] > h.slice[max] {
28+
max = r
29+
}
30+
//log.Printf("MaxHeapify(%v): l,r=%v,%v; max=%v\t%v\n", i, l, r, max, h.slice)
31+
if max != i {
32+
h.slice[i], h.slice[max] = h.slice[max], h.slice[i]
33+
h.MaxHeapify(max)
34+
}
35+
}
36+
37+
func (h MaxHeap) size() int { return h.heapSize } // ???
38+
39+
func heapSort(slice []int) []int {
40+
h := BuildMaxHeap(slice)
41+
//log.Println(slice)
42+
for i := len(h.slice) - 1; i >= 1; i-- {
43+
h.slice[0], h.slice[i] = h.slice[i], h.slice[0]
44+
h.heapSize--
45+
h.MaxHeapify(0)
46+
if i == len(h.slice)-1 || i == len(h.slice)-3 || i == len(h.slice)-5 {
47+
element := (i - len(h.slice)) * -1
48+
fmt.Println("Heap after removing ", element, " elements")
49+
fmt.Println(h.slice)
50+
51+
}
52+
}
53+
return h.slice
54+
}
55+
56+
A9B7 func main() {
57+
s1 := rand.NewSource(time.Now().UnixNano())
58+
r1 := rand.New(s1)
59+
s := make([]int, 20)
60+
for index, _ := range s {
61+
s[index] = r1.Intn(400)
62+
}
63+
fmt.Println("Randomly generated array:")
64+
fmt.Println(s)
65+
h := BuildMaxHeap(s)
66+
fmt.Println("\nInital Heap: ")
67+
fmt.Println(h.slice, "\n")
68+
69+
s = heapSort(s)
70+
fmt.Println("\nFinal List:")
71+
fmt.Println(s)
72+
}

sorts/Radix.go

Lines changed: 0 additions & 81 deletions
This file was deleted.

0 commit comments

Comments
 (0)
0