Last active
July 13, 2019 11:48
-
-
Save pdkproitf/ee93fc6a828f90ed44b85cb8dafa8db6 to your computer and use it in GitHub Desktop.
Bubble Sort in Ruby
This file contains hidden or 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
# 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