From: Michael W Ryder Date: 2010-02-04T13:22:15+09:00 Subject: Re: [Chris Pine] Chapter 7 - Sorting Arrays without .sort On 2/3/2010 5:53 PM, Ryan Davis wrote: > > On Feb 3, 2010, at 15:33 , Siep Korteling wrote: > >> Don't worry about the size of the array, ruby does take care of that. >> Don't worry about the order, strings know if they are "bigger" than >> another string. >> Aldric Giacomoni adheres to the principle: go find it out for yourself, >> and he's right; that's the way to go. But if you are like me, a relative >> simple concept like recursion takes a long time to sink in, and a did >> not find (in my time) any resources which explained it in terms I >> understood. Here's my take at explaining (in code): > > I'd disagree in principal with Aldric's advice. For starters, your original instructions say: > > "Let's write a program which asks us to type in as many words as we want > (one word per line, continuing until we just press Enter on an empty > line), and which then repeats the words back to us in alphabetical > order. > Try writing the above program without using the sort method." > > Start smaller. First write the program using Array#sort. So: > > + take user input until an empty line > + add each user input to an array > + print it back out sorted (for starters, using Array#sort). > > Once you have that down, THEN work on replacing the call to Array#sort with Array#mysort (or whatever). > Wouldn't it be easier to just sort the data as it is input, a simple insert sort? >> p recursive_sort!(["xenophobia", "foo","baz", "aardvark","bezerk"]) > > Make this easier by doing the following: > > if $0 == __FILE__ then > require 'test/unit' > > class TestSort< Test::Unit::TestCase > def test_mysort > input = ["xenophobia", "foo","baz", "aardvark","bezerk"] > expect = %w(aardvark baz bezerk foo xenophobia) # prettier, no? > > assert_equal expect, input.mysort > end > end > end > > add that to the bottom of your sort algorithm, or in a separate file (exclude the surrounding if, and be sure to require your sort algorithm). When you run it, you'll get a failure... now make it pass.