Created
August 13, 2013 19:53
-
-
Save aghyad/6224988 to your computer and use it in GitHub Desktop.
Algorithms in Ruby: counting sort (a variant of the 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_counting_sort | |
count = [] | |
a = self | |
puts a.inspect | |
m = a.first | |
a.each do |x| | |
m = x if m < x | |
end | |
i=0 | |
while i <= m | |
count << 0 | |
i+=1 | |
end | |
a.each do |x| | |
count[x.to_i] += 1 | |
end | |
sorted_arr = [] | |
i = 0 | |
count.each do |x| | |
(1..x).each { |c| sorted_arr << i } if x != 0 | |
i+=1 | |
end | |
return sorted_arr | |
end | |
end | |
############################################################################################################## | |
# puts [1,68455,8956,13,65,65,456,48,5,88,99,6,3,0,1,2,0,2,0,2,5,8,99,999,66].aghyad_counting_sort.inspect | |
# OUTPUT ==> [0, 0, 0, 1, 1, 2, 2, 2, 3, 5, 5, 6, 8, 13, 48, 65, 65, 66, 88, 99, 99, 456, 999, 8956, 68455] | |
############################################################################################################## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment