Created
February 11, 2018 11:36
-
-
Save noloman/d82c03aa0e47016cce9f3d4957aaf9d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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