【发布时间】:2014-08-13 02:03:19
【问题描述】:
我正在尝试使用递归创建自己的 .sort 方法作为红宝石书中的练习,但由于某种原因,他们还没有教我宇宙飞船操作员。我的代码用于获取最小值 - 苹果 - 并将其放入排序数组中,它甚至使用递归重复,并重置数组以重复添加第二小的单词的过程。问题是由于某种原因它删除了最小的单词-apple-,我不知道为什么。我知道我的想法 - 在 else myArray.length == 1 语句中,当我将元素从数组中弹出时,但为什么它也从 sortedArray 中删除?
sortedArray 以值 apple 结束,然后当它进行递归时,它应该是 sortedArray = ['apple', 'banana' ...] 但它删除了苹果,然后它删除了香蕉等......直到我最终得到 sortedArray = ['昆西']
我尝试将我的数组移动到多个位置,并且我尝试在多个位置添加到 sortedWords 数组,但它总是删除或重置 sortedWords 数组。
看起来我真的很接近,因为我已经完成了字母排序工作。如何让它将所有项目添加到 sortedWords 数组?
ArrayofWords = ['cat', 'dog', 'bat', 'elephant', 'apple', 'banana', 'quincy', 'boo']
# Why is it deleting, or replacing my sortedWords array? If you run this code you will notice that the sortedWords array
# is giving me the smallest word in the array, but then I add the recursive part, and somehow the previous smallestword
#gets deleted... but I have never in any part of my code say delete or replace the sorted array...
def sortTheArray myArray
unsortedWords = []
sortedWords = []
smallestValue = ''
while myArray.length != 0
if myArray.first < myArray.last
unsortedWords.push(myArray.last)
myArray.pop
elsif myArray.first > myArray.last
unsortedWords.push(myArray.first)
myArray.delete_at(0)
else myArray.length == 1
sortedWords.push(myArray.first)
myArray.pop # This is my problem area I think???
end # if else
#puts 'sorted words'
#puts sortedWords
#puts 'unsortedWords'
#puts unsortedWords
end # while
puts 'sorted words'
puts sortedWords
puts 'unsortedWords'
puts unsortedWords
myArray = unsortedWords
while myArray.length > 0
sortTheArray myArray
end #while
end # sortTheArray
sortTheArray ArrayofWords
大部分puts都没有必要,我只是想弄清楚问题出在哪里。
【问题讨论】:
-
对不起,开头写错了标题。昨晚我在问一个问题,它保存了,所以我忘了改标题。