开发者

Trying to write sort method

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:

  1. What is a wrapper method, and why do I need one? (I put on in the code, I think).
  2. 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 unsorte开发者_JS百科d[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!


1) There is nothing special going on here. We are using plain English (albeit metaphorically). A wrapper method is a method which is a wrapper. A wrapper is a thing which wraps. You are wrapping the word_sorter method with the sort method. You "need" it for convenience: it would be strange for the sort method to expect an empty list for its second parameter when you call it from outside. The wrapping takes into account the fact that the obvious interface for the recursion differs from the obvious interface for the outside world.

2) Take a close look at how the code for handling unsorted[0] >= unsorted[1] differs from the else case (i.e. when unsorted[0] < unsorted[1]).

3) Try describing your algorithm in English first. And then try putting out a few playing cards and testing your algorithm by following it, to the letter.

4) A working sort algorithm will only need to be called once. So work out a proper sorting algorithm, and then only call it once - outside the loop, after you've read in all the values to sort. You might also want to actually call words_put.


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>=2 condition. Thus now sorted=[2].

There are two issues with this one already.

  1. 2 isn't the first entry in the sorted list. There must be an issue with your algorithm being not able to sort any input.
  2. The array unsorted isn't changed at all and thus it will loop with this one forever, yielding sorted=[2,2,2,2,2.....].


"Stack level too deep" implies that you have infinite recursion going on. It doesn't look like the unsorted list gets shorter in any of your branches in word_sorter, so it will keep running forever.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜