-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucket-sort.go
62 lines (50 loc) · 1.13 KB
/
bucket-sort.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
54
55
56
57
58
59
60
61
package main
import "fmt"
//SlotSize is # 10 means each slot's size is 0.1
const SlotSize = 10
//Array wrapper for the 2d array
type Array struct {
array[] float32
}
func (a *Array) insertionSort() {
array := a.array
for i := 1; i < len(array); i++ {
value := array[i]
j := i - 1
for j >= 0 && array[j] > value {
array[j+1] = array[j]
j--
}
array[j+1] = value
}
}
func bucketSort(array []float32) []float32 {
buckets := make([]Array, SlotSize)
for i := 0; i < len(array); i++ {
var subIndex int = int(array[i] * SlotSize)
bucket := &buckets[subIndex]
bucket.array = append(bucket.array, array[i])
}
for i := range buckets {
buckets[i].insertionSort()
}
var sortedBuckets []float32
for i := range array {
sortedBucket := buckets[i].array
sortedBuckets = append(sortedBuckets, sortedBucket...)
}
return sortedBuckets
}
func print(buckets []float32) {
for i := range buckets {
fmt.Println(buckets[i])
}
}
func testBucketSort() {
fmt.Println("***")
fmt.Println("Bucket sort")
fmt.Println()
array := []float32{0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}
buckets := bucketSort(array)
print(buckets)
}