Skip to content

Instantly share code, notes, and snippets.

@aghyad
Last active December 21, 2015 00:59
Show Gist options
  • Save aghyad/6224347 to your computer and use it in GitHub Desktop.
Save aghyad/6224347 to your computer and use it in GitHub Desktop.
Algorithms in Ruby: Radix Sort
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]
####################################################################################
@aghyad
Copy link
Author

aghyad commented Aug 13, 2013

For more info about Radix sort:
http://en.wikipedia.org/wiki/Radix_sort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment