MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Bucket

Function Bucket

sort/bucketsort.go:7–46  ·  view source on GitHub ↗

Bucket sorts a slice. It is mainly useful when input is uniformly distributed over a range.

(arr []T)

Source from the content-addressed store, hash-verified

5// Bucket sorts a slice. It is mainly useful
6// when input is uniformly distributed over a range.
7func Bucket[T constraints.Number](arr []T) []T {
8 // early return if the array too small
9 if len(arr) <= 1 {
10 return arr
11 }
12
13 // find the maximum and minimum elements in arr
14 max := arr[0]
15 min := arr[0]
16 for _, v := range arr {
17 if v > max {
18 max = v
19 }
20 if v < min {
21 min = v
22 }
23 }
24
25 // create an empty bucket for each element in arr
26 bucket := make([][]T, len(arr))
27
28 // put each element in the appropriate bucket
29 for _, v := range arr {
30 bucketIndex := int((v - min) / (max - min) * T(len(arr)-1))
31 bucket[bucketIndex] = append(bucket[bucketIndex], v)
32 }
33
34 // use insertion sort to sort each bucket
35 for i := range bucket {
36 bucket[i] = Insertion(bucket[i])
37 }
38
39 // concatenate the sorted buckets
40 sorted := make([]T, 0, len(arr))
41 for _, v := range bucket {
42 sorted = append(sorted, v...)
43 }
44
45 return sorted
46}

Callers

nothing calls this directly

Calls 1

InsertionFunction · 0.85

Tested by

no test coverage detected