我正在学习Ruby和递归方法。我正在处理的问题是排序数组中的单词。我的递归方法阵列正确排序,然而,我每次运行通过法阵,从最初的阵列(“字”)的最后一个字被删除:排序时通过递归排序删除/弹出的单词
# Word sorter
def sort(some_array)
recursive_sort(some_array, [])
end
def recursive_sort(unsorted_array, sorted_array)
if unsorted_array.length <= 0
return sorted_array
end
smallest = unsorted_array.pop
unsorted = []
unsorted_array.each do |word|
if word < smallest
unsorted << smallest
smallest = word
else
unsorted << word
end
end
sorted_array << smallest
recursive_sort(unsorted,sorted_array)
end
words = ['hi', 'welcome', 'bye', 'idk', 'where', 'apples', 'bananas']
sort(words)
puts "#{words}"
sort(words)
puts "#{words}"
sort(words)
puts "#{words}"
这是发生了什么“的话“array:
["hi", "welcome", "bye", "idk", "where", "apples"]
["hi", "welcome", "bye", "idk", "where"]
["hi", "welcome", "bye", "idk"]
为什么会发生这种情况?
我personnally想补充一个!到'recursive_sort'来通知用户它有一个副作用。 – floum
我现在看到了,谢谢你的回答! – ckdub