Skip to content

Instantly share code, notes, and snippets.

@noloman
Created February 11, 2018 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noloman/d82c03aa0e47016cce9f3d4957aaf9d4 to your computer and use it in GitHub Desktop.
Save noloman/d82c03aa0e47016cce9f3d4957aaf9d4 to your computer and use it in GitHub Desktop.
def bubble_sort(array)
sorted = false
until sorted
puts "Original array: #{array}"
sorted = true
0.upto(array.length - 2) do |i|
res = block_given? ? yield(array[i], array[i + 1]) : array[i] - array[i + 1]
if res > 0
sorted = false
array[i], array[i + 1] = array[i + 1], array[i]
end
end
end
puts "Final array: #{array}"
end
bubble_sort([1,9,3,6,2,8])
bubble_sort(["hello", "holitaholaholita", "hi"]) { |left, right| left.length - right.length }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment