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)
|
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__
|
||||||
|
|
Loading…
Add table
Reference in a new issue