Created
March 29, 2011 10:19
-
-
Save xianhuazhou/892132 to your computer and use it in GitHub Desktop.
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
def bubble_sort(array) | |
size = array.size - 1 | |
0.upto(size) do |i| | |
i.upto(size) do |j| | |
array[i], array[j] = array[j], array[i] if array[i] > array[j] | |
end | |
end | |
array | |
end | |
def insert_sort(array) | |
(0...array.size).each do |i| | |
tmp = array[i] | |
j = i - 1 | |
while j >= 0 and array[j] > tmp do | |
array[j + 1] = array[j] | |
j -= 1 | |
array[j + 1] = tmp | |
end | |
end | |
array | |
end | |
def stack_sort(array) | |
size = array.size - 1 | |
result = [] | |
ary = array.clone | |
0.upto(size) do |index| | |
result << find_min(array[index], ary) | |
end | |
result | |
end | |
def find_min(el, ary) | |
min = ary.first | |
min_index = 0 | |
ary.each_with_index do |el, index| | |
if el < min | |
min = el | |
min_index = index | |
end | |
end | |
ary.delete_at min_index | |
min | |
end | |
data = (1..1000).to_a.shuffle | |
t = Time.now.to_f | |
bubble_sort(data.clone) | |
puts "bubble sort: #{Time.now.to_f - t}" | |
puts "------------" | |
t = Time.now.to_f | |
insert_sort(data.clone) | |
puts "Insert sort: #{Time.now.to_f - t}" | |
puts "------------" | |
t = Time.now.to_f | |
select_sort(data.clone) | |
puts "Stack sort: #{Time.now.to_f - t}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: