Skip to content

Commit c160c5e

Browse files
authored
Create BucketSort.go
桶排序
1 parent 27f631a commit c160c5e

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

go/13_sorts/BucketSort.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package LinearSort
2+
3+
import (
4+
"algorithm/Sort"
5+
"fmt"
6+
)
7+
8+
// 桶排序
9+
10+
// 获取待排序数组中的最大值
11+
func getMax(a []int)int{
12+
max := a[0]
13+
for i:=1; i<len(a); i++{
14+
if a[i] > max{
15+
max = a[i]
16+
}
17+
}
18+
return max
19+
}
20+
21+
22+
func BucketSort(a []int) {
23+
num := len(a)
24+
if num <= 1{
25+
return
26+
}
27+
max := getMax(a)
28+
buckets := make([][]int, num) // 二维切片
29+
30+
index :=0
31+
for i:=0; i< num; i++{
32+
index = a[i]*(num -1) / max // 桶序号
33+
buckets[index] = append(buckets[index],a[i]) // 加入对应的桶中
34+
}
35+
36+
tmpPos := 0 // 标记数组位置
37+
for i := 0; i < num; i++ {
38+
bucketLen := len(buckets[i])
39+
if bucketLen > 0{
40+
Sort.QuickSort(buckets[i]) // 桶内做快速排序
41+
copy(a[tmpPos:], buckets[i])
42+
tmpPos += bucketLen
43+
}
44+
}
45+
46+
}
47+
48+
49+
// 桶排序简单实现
50+
func BucketSortSimple(source []int) {
51+
if len(source)<=1{
52+
return
53+
}
54+
array := make([]int, getMax(source)+1)
55+
for i:=0; i<len(source); i++{
56+
array[source[i]] ++
57+
}
58+
fmt.Println(array)
59+
c := make([]int,0)
60+
for i:=0; i<len(array); i++{
61+
for array[i] != 0 {
62+
c = append(c, i)
63+
array[i] --
64+
}
65+
}
66+
copy(source,c)
67+
68+
}
69+

0 commit comments

Comments
 (0)