Skip to content

Instantly share code, notes, and snippets.

@ichistmeinname
Forked from universal/sort.rb
Last active January 22, 2016 14:48
Show Gist options
  • Save ichistmeinname/70469daa7314503753c1 to your computer and use it in GitHub Desktop.
Save ichistmeinname/70469daa7314503753c1 to your computer and use it in GitHub Desktop.
# min_sort
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
# Swaps element at index position `i` in `a` with
# element at index position `j` in `a`
def swap!(a,i,j)
dummy = a[i];
a[i] = a[j];
a[j] = dummy;
end;
# Finds minimum element of an array `a`,
# beginning from `pos`
def min_pos_from(a,pos)
min_pos = pos;
for i in pos+1 .. a.size-1 do
if a[i] < a[min_pos] then
min_pos = i;
end;
end;
return min_pos;
end;
def min_sort!(a)
for i in 0 .. a.size-2 do
#da einelementiges Array immer sortiert
pos = min_pos_from(a,i);
swap!(a,i,pos);
end;
return a;
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
def max_pos_until(arr,pos)
max_pos = 0;
for i in 0..pos do
if arr[i] > arr[max_pos] then
max_pos = i;
end;
end;
return max_pos;
end;
def max_sort!(a)
# Wir müssen das größte Element
# ganz nach rechts schieben!
for i in 0..a.size-2 do
right_pos = a.size-1-i;
max = max_pos_until(a,right_pos);
swap!(a,max,right_pos);
end;
return a;
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(unsorted.first)
Benchmark.bm do |bm|
bm.report("min") do
unsorted.each do |u|
min_sort u
end
end
bm.report("min - a") do
unsorted_a.each do |u|
min_sort u
end
end
bm.report("min!") do
unsorted.each do |u|
min_sort! u
end
end
bm.report("min! - a") do
unsorted_a.each do |u|
min_sort! u
end
end
bm.report("max") do
unsorted.each do |u|
max_sort u
end
end
bm.report("max - a") do
unsorted_a.each do |u|
max_sort u
end
end
bm.report("max!") do
unsorted2.each do |u|
max_sort! u
end
end
bm.report("max! - a") do
unsorted2_a.each do |u|
max_sort! u
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment