-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket_sort.go
More file actions
46 lines (37 loc) · 718 Bytes
/
bucket_sort.go
File metadata and controls
46 lines (37 loc) · 718 Bytes
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
package sort
import (
"math"
"golang.org/x/exp/constraints"
)
func BucketSort[T constraints.Integer](arr []T) []T {
n := len(arr)
var maxVal, minVal T
for _, v := range arr {
if v > maxVal {
maxVal = v
}
if v < minVal {
minVal = v
}
}
rangeVal := maxVal - minVal
bucket := make([][]T, n)
for i := 0; i < n; i++ {
bucket[i] = make([]T, 0)
}
for _, v := range arr {
index := int(math.Floor(float64(n) * float64((v-minVal)/rangeVal)))
if index == n {
index--
}
bucket[index] = append(bucket[index], v)
}
for i := 0; i < n; i++ {
InsertionSort(bucket[i])
}
sorted := make([]T, 0, n)
for i := 0; i < n; i++ {
sorted = append(sorted, bucket[i]...)
}
return sorted
}