github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/bucket.go (about) 1 package sort 2 3 /* 4 The process of bucket sort can be understood as scatter-gather approach. 5 Here, elements are first scattered into buckets then the elements in each buckets are sorted. 6 Finally, the elements are gathered in order. 7 8 1.创建固定数量的 buckets 9 2.bucket size 最好通过归一化的处理后平均划分(也不是绝对均分),大于 0 小于 1 的 float 可以通过扩大相同倍数(> 1 整数) 10 来进行 size 划分 11 */ 12 13 func BucketSort(arr []int) { 14 n := len(arr) 15 BUCKET_SIZE := 10 16 buckets := make([][]int, BUCKET_SIZE) 17 max := getMax(arr, n) 18 var interval int = max / BUCKET_SIZE 19 if max%BUCKET_SIZE > 0 { 20 interval++ 21 } 22 23 for i := 0; i < n; i++ { 24 bucketIdx := arr[i]/interval - 1 25 if arr[i]%interval > 0 { 26 bucketIdx++ 27 } else if bucketIdx == -1 { 28 bucketIdx = 0 29 } 30 31 buckets[bucketIdx] = append(buckets[bucketIdx], arr[i]) 32 } 33 34 origIdx := 0 35 for i := 0; i < BUCKET_SIZE && origIdx < n; i++ { 36 blen := len(buckets[i]) 37 if blen > 0 { 38 InsertSortSimplify(buckets[i]) 39 40 for j := 0; j < blen; j++ { 41 arr[origIdx] = buckets[i][j] 42 origIdx++ 43 } 44 } 45 } 46 }