DEV Community

Wilson Tovar
Wilson Tovar

Posted on

Bubble Sort in Ruby

Original publication: Seis Algoritmos en Ruby - @Kinduff

It is the most basic way of arranging a collection. It iterate on every value and it compares with the following one, they are exchanged of being necessary, the iteration repeats itself until all the values are not exchangeable.

def sort(values) length = values.size - 2 swapped = true while swapped swapped = false 0.upto(length) do |i| if values[i] > values[i+1] values[i], values[i+1] = values[i+1], values[i] swapped = true end end end return values end sort([7, 4, 5, 2, 9, 1]) # => # 7, 4, 5, 2, 9, 1 # 4, 5, 2, 7, 1, 9 # 4, 2, 5, 1, 7, 9 # 2, 4, 1, 5, 7, 9 # 2, 1, 4, 5, 7, 9 # 1, 2, 4, 5, 7, 9 
Enter fullscreen mode Exit fullscreen mode

;)

Top comments (0)