ratio/ruby/bubble_sort.rb

33 lines
676 B
Ruby
Raw Permalink Normal View History

2017-03-11 23:43:13 -07:00
# Copyright (C) 2017 Kevin Cotugno
# All rights reserved
#
# Distributed under the terms of the MIT software license. See the
# accompanying LICENSE file or http://www.opensource.org/licenses/MIT.
def bubble_sort(unsorted)
2017-03-12 09:42:14 -07:00
count = unsorted.count
2017-03-11 23:43:13 -07:00
count.times do |i|
(count - i - 1).times do |j|
2017-03-12 09:42:14 -07:00
if unsorted[j] > unsorted[j+1]
t = unsorted[j]
unsorted[j] = unsorted[j+1]
unsorted[j+1] = t
2017-03-11 23:43:13 -07:00
end
end
end
2017-03-12 09:42:14 -07:00
unsorted
2017-03-11 23:43:13 -07:00
end
print 'How many elements? '
num = gets.to_i
elements = Array.new(num) do |i|
print "Enter element #{i + 1}: "
gets.to_i
end
2017-03-12 09:42:14 -07:00
print "Unsorted: #{elements}\n"
print "Sorted: #{bubble_sort(elements)}\n"