Bubble Sort in Ruby
def bubble_sort(array)
n = array.length
swapped = true
while swapped do
swapped = false
(n - 1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
swapped = true
end
end
end
array
end
arr = [2,3,100,3,5,4,10,7]
p bubble_sort(arr) # => [2, 3, 3, 4, 5, 7, 10, 100]
Written by Maynard Cabalitan
Related protips
2 Responses
thanks
over 1 year ago
·
bubble sort mark
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#