-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathradix_sort.sf
More file actions
32 lines (29 loc) · 770 Bytes
/
radix_sort.sf
File metadata and controls
32 lines (29 loc) · 770 Bytes
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
#!/usr/bin/ruby
#
## https://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
#
class Array {
method radix_sort(base=10) {
var arr = self.clone
var rounds = ([arr.minmax].map{.abs}.max.ilog(base) + 1)
for i in (0..rounds) {
var buckets = (2*base -> of {[]})
var base_i = base**i
for n in arr {
var digit = (n/base_i % base)
digit += base if (0 <= n)
buckets[digit].append(n)
}
arr = buckets.flat
}
return arr
}
}
for arr in [
[1, 3, 8, 9, 0, 0, 8, 7, 1, 6],
[170, 45, 75, 90, 2, 24, 802, 66],
[170, 45, 75, 90, 2, 24, -802, -66],
[100000, -10000, 400, 23, 10000],
] {
say arr.radix_sort
}