Created
June 18, 2018 17:04
-
-
Save MagnusRufum/e3f584444e698785fc65085309bdd5a2 to your computer and use it in GitHub Desktop.
Bubble Sort Ruby solution for The Odin Project
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) | |
loop do | |
swapped = false | |
(array.length-1).times do |i| | |
if array[i] > array[i+1] | |
array[i], array[i+1] = array[i+1], array[i] | |
swapped = true | |
end | |
end | |
break if not swapped | |
end | |
array | |
end | |
def bubble_sort_by(array) | |
loop do | |
swapped = false | |
(array.length-1).times do |i| | |
if yield(array[i], array[i+1]) > 0 | |
array[i], array[i+1] = array[i+1], array[i] | |
swapped = true | |
end | |
end | |
break if not swapped | |
end | |
array | |
end | |
puts (bubble_sort_by(["hello", "hey", "hi"]) do |left, right| | |
left.length - right.length | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment