forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
radixsort.go
44 lines (33 loc) · 891 Bytes
/
radixsort.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
package radixsort
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] = bucket[(slice[index]/exp) % 10] + 1
}
for index := 1; index < 10; index++ {
bucket[index] = bucket[index] + bucket[index-1]
}
for index := length-1; index >= 0; index-- {
bucket[(slice[index] / exp) % 10] = bucket[(slice[index] / exp) % 10] - 1
temp[bucket[(slice[index] / exp) % 10]] = slice[index]
}
for index := 0; index < length; index++ {
slice[index] = temp[index]
}
exp = exp * 10
}
}