mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-30 20:34:53 +01:00
Merge pull request #186 from shanshaji/shan/bubble_sort_fix
New improved implementation of bubble sort
This commit is contained in:
commit
1998d6137e
1 changed files with 12 additions and 12 deletions
|
@ -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__
|
||||
|
|
Loading…
Add table
Reference in a new issue