Trying to sort an array by writing my own sort method using recursion (Pine’s book). Saw some other examples on stackoverflow, but my code looks different from them. Two things I don’t understand so far:
- What is a wrapper method, and why do I need one? (I put on in the code, I think).
- How to fix the “stack level too deep” error.
EDIT: New code updated, working but not correct.
Here’s what I have so far:
def word_sorter unsorted, sorted
if unsorted[1] == nil
sorted.push unsorted[0]
words_put(sorted)
elsif unsorted[0] <= unsorted[1]
sorted.push unsorted[0]
unsorted.shift
word_sorter(unsorted, sorted)
else
unsorted.push unsorted[0]
unsorted.shift
word_sorter(unsorted, sorted)
end
end
def words_put sorted
puts 'these are your words now organized.'
sorted.compact!
puts sorted.join(', ')
Process.exit
end
unsorted = Array.new
sorted = Array.new
puts 'list as many words as you want. I will sort them... I think'
while unsorted.last != ''
unsorted.push gets.chomp
if unsorted.last == ''
unsorted.pop
word_sorter(unsorted, sorted)
end
end
Thanks!
You should first try your code by some simple examples. E.g. use the list
[3,2,1]as input.In the first call it will match the
3>=2condition. Thus nowsorted=[2].There are two issues with this one already.
2isn’t the first entry in the sorted list. There must be an issue with your algorithm being not able to sort any input.unsortedisn’t changed at all and thus it will loop with this one forever, yieldingsorted=[2,2,2,2,2.....].