-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.go
54 lines (43 loc) · 879 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
53
54
package mysorts
import (
"math"
)
// RadixSort implement a decimal based radix sort
func RadixSort(in []int) {
if len(in) <= 1 {
return
}
// find max value from in
k := findMaxElement(in)
s := 10 // decimal
var d int
newK := k
for newK > 0 {
d++
newK /= s
}
internalCountingSort := func(in []int, p int) { // MUST be stable sort
counting := make([]int, s, s) // all elements will be initialized by 0
out := make([]int, len(in), len(in))
for _, v := range in {
pv := (v / p) % s
counting[pv]++
}
for i := 1; i < s; i++ {
counting[i] += counting[i-1]
}
for j := len(in) - 1; j >= 0; j-- {
v := in[j]
pv := (v / p) % s
out[counting[pv]-1] = v
counting[pv]--
}
// copy out back to in
in = in[:0]
in = append(in, out...)
}
for i := 0; i < d; i++ {
p := (int)(math.Pow10(i))
internalCountingSort(in, p)
}
}