定义方法在Ruby中使用递归? - defining sort method in Ruby using recursion?

- 此内容更新于:2016-02-01
主题:

我正在LTP的克里斯•松ch10-试图使用递归创建我自己的排序方法。不使用递归我做过,但是我不知道为什么这个递归方法是行不通的。它返回一个空数组&然后两个“零”数组。

原文:

I'm working on LTP by Chris Pine, ch 10 - trying to create my own sort method using recursion. I've done it without recursion, but I can't figure out why this recursive method doesn't work. It returns an empty array & then two "nil" arrays.

words = ["this", "that", "Patrick", "Svetlana", "USA", "aviation", "that"]

def sort_r(array, sorted_array=[])
  sorted_array.push(array.min)

  if array != []
    array.delete_at(array.index(array.min))
    sort_r(array, sorted_array)
  end

  p sorted_array
end

p sort_r(words)
网友:我得到,请分享你的期望输出和实际输出

(原文:I get ["Patrick", "Svetlana", "USA", "aviation", "that", "that", "this", nil] - please share your expected output and actual output)

解决方案:
添加导致去年年底迭代递归的是在这种情况下,从空数组,你推到第一线的功能。您需要检查后删除数组的最小值,避免调用递归方法如果[]可以简化代码如下:
原文:

nil gets added at the end of result in last iteration of recursion by as array is [] in that case, and you push an min from empty array into sorted_array in first line of your function.

You need to check if array != [] after removing the min from the array and avoid calling the recursive method if its []


Your code can be simplified to below:

words = ["this", "that", "Patrick", "Svetlana", "USA", "aviation", "that"]

def sort_r(array, sorted_array=[])
  sorted_array << array.delete_at(array.index(array.min))
  sort_r(array, sorted_array) unless array.size.zero?
  sorted_array
end

p sort_r(words)
#=> ["Patrick", "Svetlana", "USA", "aviation", "that", "that", "this"]
楼主:很好,谢谢你的帮助。

(原文:Excellent, thanks for the help.)