-
Notifications
You must be signed in to change notification settings - Fork 267
/
radix_sort.go
52 lines (40 loc) · 883 Bytes
/
radix_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
package main
import "fmt"
func RadixSort(slice []int) {
if len(slice) == 0 {
return
}
length := len(slice)
higher := slice[0]
exp := 1
var temp []int
for index := 0; index < length; index++ {
temp = append(temp, 0)
if slice[index] > higher {
higher = slice[index]
}
}
for higher/exp > 0 {
var bucket [10]int
for index := 0; index < length; index++ {
bucket[(slice[index]/exp)%10]++
}
for index := 1; index < 10; index++ {
bucket[index] += bucket[index-1]
}
for index := length - 1; index >= 0; index-- {
bucket[(slice[index]/exp)%10]--
temp[bucket[(slice[index]/exp)%10]] = slice[index]
}
for index := 0; index < length; index++ {
slice[index] = temp[index]
}
exp *= 10
}
}
func main() {
slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4}
fmt.Println("Slice:", slice)
RadixSort(slice)
fmt.Println("RadixSort:", slice)
}