Skip to content

Instantly share code, notes, and snippets.

@xianhuazhou
Created March 29, 2011 10:19
Show Gist options
  • Save xianhuazhou/892132 to your computer and use it in GitHub Desktop.
Save xianhuazhou/892132 to your computer and use it in GitHub Desktop.
sort
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}"
@xianhuazhou
Copy link
Author

Result:

bubble sort: 0.13756442070007324
------------
Insert sort: 0.07863044738769531
------------
Stack sort: 0.05679774284362793

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment