Created
July 8, 2019 15:43
-
-
Save korakotlee/988adebea689a2bdd36d6b96278d89cc to your computer and use it in GitHub Desktop.
ruby bubble sort
This file contains 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
def bubble_sort(list) | |
return list if list.size <= 1 | |
loop do | |
sorted = true | |
index_right = 2 | |
0.upto(list.size-index_right) do |i| | |
if list[i] > list[i+1] | |
list[i], list[i+1] = list[i+1], list[i] | |
sorted = false | |
end | |
end | |
index_right += 1 # the right of index_right are already sorted | |
break if sorted # no swap | |
end | |
list | |
end | |
array = [6, 5, 3, 1, 8, 7, 2, 4] | |
p bubble_sort(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment