Skip to content

Instantly share code, notes, and snippets.

@pdkproitf
Last active July 13, 2019 11:48
Show Gist options
  • Save pdkproitf/ee93fc6a828f90ed44b85cb8dafa8db6 to your computer and use it in GitHub Desktop.
Save pdkproitf/ee93fc6a828f90ed44b85cb8dafa8db6 to your computer and use it in GitHub Desktop.
Bubble Sort in Ruby
# Algorithm: https://www.geeksforgeeks.org/bubble-sort/
def bubble_sort_recursive(array)
limit_sort = array.length - 1
return array if limit_sort <= 1
print "#{limit_sort} ----> #{array}\n"
for i in 0...limit_sort
next unless array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
end
bubble_sort_recursive(array[0..-2]) + [array[-1]]
end
def bubble_sort(array)
limit_sort = array.length - 1
while limit_sort >= 1
for i in 0...limit_sort
next unless array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
end
print "#{limit_sort} ----> #{array}\n"
limit_sort -= 1
end
array
end
arr = [3,7,8,4,10,16,2,1,12]
puts '------------------------------BUBBLE SORT O(n^2)--------------------------'
puts "---------bubble_sort_recursive-------------"
print "#{bubble_sort_recursive(arr)}\n"
puts "---------------bubble_sort-----------------"
print "#{bubble_sort(arr)}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment