Merge pull request #186 from shanshaji/shan/bubble_sort_fix

New improved implementation of bubble sort
This commit is contained in:
Vitor Oliveira 2021-12-22 13:25:02 -08:00 committed by GitHub
commit 1998d6137e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,19 +1,19 @@
def bubble_sort(array)
n = array.length
loop 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
array_length = array.length
return array if array_length <= 1
unsorted_until_index = array_length - 1
sorted = false
until sorted
sorted = true
0.upto(unsorted_until_index - 1) do |i|
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
sorted = false
end
end
break unless swapped
unsorted_until_index -= 1
end
array
return array
end
if $0 == __FILE__