forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.rb
62 lines (50 loc) · 1.03 KB
/
radix_sort.rb
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
55
56
57
58
59
60
61
62
# frozen_string_literal: true
# Sort an array using the RadixSort algorithm
class RadixSort
attr_reader :array_sorted
def initialize
@array_sorted = []
end
def init(array)
radix_sort(array)
end
private
def radix_sort(array)
max_value = array.max
exp = 0
until max_value.zero?
exp += 1
max_value = (max_value / 10)
end
(0...exp).each do |i|
array = radix(array, i)
end
@array_sorted = array
end
def radix(array, exp = 0)
array_c = Array.new(10, 0)
result = Array.new(array.length)
m = 10**(exp + 1)
n = 10**exp
array.each do |value|
num = (value % m) / n
array_c[num] += 1
end
(1...10).each do |i|
array_c[i] = array_c[i - 1] + array_c[i]
end
i = (array.length - 1)
until i.negative?
value = array[i]
num = (value % m) / n
array_c[num] -= 1
result[array_c[num]] = value
i -= 1
end
result
end
end
# test
r_s = RadixSort.new
r_s.init([1, 4, 10, 2, 3, 32, 0])
p r_s.array_sorted