Bubble Sort

Sort an array using the bubble sort algorithm by repeatedly swapping adjacent elements.

Code

Algorithms
a = arr.dup
(0...a.length).each do |i|
  (0...a.length - i - 1).each do |j|
    a[j], a[j + 1] = a[j + 1], a[j] if a[j] > a[j + 1]
  end
end
a

Parameters

Array to sort

Server

More Ruby Snippets