Skip to content

Instantly share code, notes, and snippets.

@universal
Created January 22, 2016 13:04
Show Gist options
  • Save universal/50d4190cf701fae64e27 to your computer and use it in GitHub Desktop.
Save universal/50d4190cf701fae64e27 to your computer and use it in GitHub Desktop.
# minSort
def min_sort(to_sort:)
length = to_sort.length - 1
min_index = nil
for i in 0..length
min_index = i
for j in i..length
if to_sort[j] < to_sort[min_index]
min_index = j
end
end # j loop
current = to_sort[i]
min_element = to_sort[min_index]
to_sort[i] = min_element
to_sort[min_index] = current
end # i loop
to_sort
end
def max_sort(to_sort:)
length = to_sort.length - 1
max_index = nil
for i in 0..length
max_index = length - i
for j in i..length
if to_sort[length - j] > to_sort[max_index]
max_index = length - j
end
end # j loop
current = to_sort[length - i]
max_element = to_sort[max_index]
to_sort[length - i] = max_element
to_sort[max_index] = current
end # i loop
to_sort
end
#result = max_sort to_sort: 10.times.collect { rand }
#puts result.join(" <-> ")
require 'benchmark'
unsorted = 100.times.collect {1000.times.collect { rand } }
unsorted_a = 1000.times.collect {100.times.collect { rand } }
unsorted2 = unsorted.map {|u| u.dup }
unsorted2_a = unsorted_a.map {|u| u.dup }
res = min_sort(to_sort: unsorted.first)
Benchmark.bm do |bm|
bm.report("min") do
unsorted.each do |u|
min_sort to_sort: u
end
end
bm.report("min - a") do
unsorted_a.each do |u|
min_sort to_sort: u
end
end
bm.report("max") do
unsorted2.each do |u|
max_sort to_sort: u
end
end
bm.report("max - a") do
unsorted2_a.each do |u|
max_sort to_sort: u
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment