Abduct:
Here is my ruby radix sort implementation. faster than quick sort but rubys built in sort is still faster by a long shot
so here is the sorts ive tested so far
bubble sort, 5.2923027 seconds per sort
Selection sort, 1.5013859 seconds per sort
quick sort, 0.1478085 seconds per sort
radix sort, 0.004200199999999999 seconds per sort
custom sort, 0.0022002000000000002 seconds per sort
ruby's sort, 0.0004 seconds per sort
Code
def radix_sort(base=10)
ary = dup
rounds = (Math.log(self.max.abs)/Math.log(base)).ceil
rounds.times do |i|
buckets = Hash.new {|h,k| h[k] = []}
ary.each do |n|
digit = (n/base**i) % base
digit = digit + base unless n<0
buckets[digit] << n
end
ary = buckets.values_at(*(0..2*base)).compact.flatten
p [i, ary] if $DEBUG
end
ary
end
Code
def customsort(array)
temp = Array.new
mylist = []
array.each do |x|
if temp[x] == nil
temp[x] = 1
else
temp[x] = temp[x] + 1
end
end
temp.each_with_index do |x, i|
if (x)
x.times do
mylist.push i
end
end
end
mylist
end
numbers = []
5000.times { numbers.push Random.rand(0..100) }
time = Benchmark.realtime do
10.times { new_numbers = customsort numbers }
end
puts "#{time / 10} seconds per sort (radix sort)"
This post was edited by Azrad on Jun 1 2013 04:10pm