Rom*_*vis 5 ruby recursion block bubble-sort
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
Run Code Online (Sandbox Code Playgroud)
程序基于块进行冒泡排序。在这种情况下,块按长度排序。所以,我得到一个本地跳转错误。花了我一点,但我想通了。当我递归调用该方法时,我没有给它块。但是我该怎么做呢?
传递块是可选的,但在这里,正如您已经理解的那样,您需要它来进行递归调用。您只需将块作为附加参数传递:
def bubble_sort_by nums, &comparator
# ...
bubble_sort_by nums, &comparator if do_it_again
# ...
end
Run Code Online (Sandbox Code Playgroud)