def bubble_sort_by nums
do_it_again = false
nums[0...-1].each_with_index do |item, index|
if yield(nums[index], nums[index + 1]) > 0
nums[index], nums[index + 1] = nums[index + 1], nums[index]
do_it_again = true
end
end
bubble_sort_by nums if do_it_again
nums
end
bubble_sort_by(["hi","hello","hey"]) do |left,right|
right.length - left.length
end
Program does a bubble sort based on a block. In this case, the block sorts by length. So, I get a local jump error. Took me a bit, but I figured it out. When I call the method recursively, I'm not giving it the block. But how do I do that?
Passing the block is optional, but here, as you already understood, you need it to make your recursive calls. You just pass the block as an additional parameter:
def bubble_sort_by nums, &comparator
# ...
bubble_sort_by nums, &comparator if do_it_again
# ...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With