Skip to content

Instantly share code, notes, and snippets.

@korakotlee
Created July 8, 2019 15:43
Show Gist options
  • Save korakotlee/988adebea689a2bdd36d6b96278d89cc to your computer and use it in GitHub Desktop.
Save korakotlee/988adebea689a2bdd36d6b96278d89cc to your computer and use it in GitHub Desktop.
ruby bubble sort
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