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