-
-
Save ncaron/a36e7aeaeda64b8e63de996c0c012278 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 to_sort | |
last = to_sort.length - 1 | |
loop do | |
sorted = true | |
for i in (0...last) | |
if to_sort[i] > to_sort[i + 1] | |
to_sort[i], to_sort[i + 1] = to_sort[i + 1], to_sort[i] | |
sorted = false | |
end | |
end | |
last -= 1 | |
break if sorted | |
end | |
to_sort | |
end | |
p(bubble_sort([4, 3, 78, 2, 0, 2]) == [0, 2, 2, 3, 4, 78]) | |
p(bubble_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]) | |
p(bubble_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]) | |
p(bubble_sort([5, -84, 42, 15, 0, 2, 2, 67]) == [-84, 0, 2, 2, 5, 15, 42, 67]) | |
def bubble_sort_by to_sort | |
last = to_sort.length - 1 | |
loop do | |
sorted = true | |
for i in (0...last) | |
if (yield(to_sort[i], to_sort[i + 1]) > 0) | |
to_sort[i], to_sort[i + 1] = to_sort[i + 1], to_sort[i] | |
sorted = false | |
end | |
end | |
last -= 1 | |
break if sorted | |
end | |
to_sort | |
end | |
p(bubble_sort_by(['hi','hello','hey']) do |left, right| | |
left.length - right.length | |
end == ['hi', 'hey', 'hello']) | |
p(bubble_sort_by([5, 3, 7, 1]) do |left, right| | |
left - right | |
end == [1, 3, 5, 7]) | |
p(bubble_sort_by([5, 3, 7, 1]) do |left, right| | |
right - left | |
end == [7, 5, 3, 1]) | |
p(bubble_sort_by(['hey', 'my', 'name', 'is', 'Niko']) do |left, right| | |
left <=> right | |
end == ['Niko', 'hey', 'is', 'my', 'name']) | |
p(bubble_sort_by(['hey', 'my', 'name', 'is', 'Niko']) do |left, right| | |
right <=> left | |
end == ['name', 'my', 'is', 'hey', 'Niko']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment