Last active
December 21, 2015 00:59
-
-
Save aghyad/6224347 to your computer and use it in GitHub Desktop.
Algorithms in Ruby: Radix Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def aghyad_radix_sort | |
round = 0 | |
bucket = [[],[],[],[],[],[],[],[],[],[]] #bucket of 10 sub-arrays | |
self.each do |x| | |
bucket[x.to_s.split('')[-1*(round+1)].to_i] << x | |
end | |
a = bucket.flatten | |
max = a.max_num_of_digits | |
while round < max | |
bucket = [[],[],[],[],[],[],[],[],[],[]] #bucket of 10 sub-arrays | |
a.each do |x| | |
bucket[x.to_s.split('')[-1*(round+1)].to_i] << x | |
end | |
a = bucket.flatten | |
round += 1 | |
end | |
return a | |
end | |
def max_num_of_digits | |
m = 1 | |
self.each do |x| | |
m = x.to_s.size if m < x.to_s.size | |
end | |
return m | |
end | |
end | |
#################################################################################### | |
# puts [46,454444431,55,8,9,66,55,7,44,1,2,0,2,33,2222].aghyad_radix_sort.inspect | |
# OUTPUT ==> [0, 1, 2, 2, 7, 8, 9, 33, 44, 46, 55, 55, 66, 2222, 454444431] | |
#################################################################################### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For more info about Radix sort:
http://en.wikipedia.org/wiki/Radix_sort