Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple program to sort a list of number ranging 1-130 in ascending order
require 'benchmark'
def smarter_way(unsorted_array, size, sorted_array)
maggic_array = Array.new(130) {|i| i = ({ i => 0 }) }
unsorted_array.each do |num|
maggic_array.each do |hash|
if hash.keys.first == num
hash[num] = hash[num] + 1
end
end
end
maggic_array.each do |k|
(1..k[k.keys.first]).each do |num|
sorted_array.push(k.keys.first)
end
end
end
def insertion_sort(unsorted_array, size, sorted_array)
(1..(size-1)).each do |i|
j = i
while (j > 0 && sorted_array[j-1] > sorted_array[j])
sorted_array[j-1],sorted_array[j] = sorted_array[j],sorted_array[j-1]
j = j-1
end
end
end
puts "Sorting Numbers"
sizes = [10,100,1000,10000,100000]
sizes.each do |size|
unsorted_array = Array.new(size) { |i| i = rand(130)}
sorted_array = Array.new
puts "Test 1 : a : Running for size: #{size}"
Benchmark.bm do |x|
x.report {
smarter_way(unsorted_array, size, sorted_array)
}
end
puts "Test 1 : b : Running for size: #{size}"
sorted_array = unsorted_array
Benchmark.bm do |x|
x.report {
insertion_sort(unsorted_array, size, sorted_array)
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment