Topic: Trouble Writing My Own Sort Method

I know there is a method called "sort" that can be called on arrays but I want to write my own to get a feel for Ruby.  I'm getting an error I can't understand.  Can anyone help?

Code:
~~~~~~~~~~~~~~~~~
unsorted = ['cat','ate','at','ball','beetle','bat']
sorted = []
def recursive_sort unsorted, sorted
    while unsorted.length > 0
        if unsorted.length == 1
            sorted.push unsorted[0]
            unsorted.pop
        else
            counter = unsorted.length
            a = 1
            y = unsorted[0]
            while counter > 0
                if y > unsorted[a]   #LINE 13
                    y = unsorted[a]
                end
                counter = counter-1
                a = a+1
            end
            sorted.push y
            unsorted.delete(y)
        end
    end
    puts sorted
end

recursive_sort unsorted, sorted
~~~~~~~~~~~~~~~~~~

I get this error message:
test.rb:13:in '>': comparison of String with nil failed (ArgumentError)

Any help would be appreciated!

Re: Trouble Writing My Own Sort Method

I'm not sure if I'm reading this right, but don't you want sorted[a] on Line 13?

Edit: Guess not. Whoops. smile

Last edited by Firanide (2007-05-29 00:31:12)

Re: Trouble Writing My Own Sort Method

I'm not too familiar myself with Ruby, but could the problem arise from using the '>' operator to compare String data types?

Re: Trouble Writing My Own Sort Method

The < and > operators can be used with strings in Ruby.  'a' is less than 'b'
For example, I just wrote and ran the following code:
if 'a' < 'b'
    puts 'yes'
else
    puts 'no'
end

The output was:
yes

Re: Trouble Writing My Own Sort Method

That would mean either unsorted[0] or unsorted[a] is nil.  This means there is no value.  My first guess without actually running it is that you are getting to the end, where you've popped everything off of unsorted, and unsorted[0] has no value.

Re: Trouble Writing My Own Sort Method

Old line 12
while counter > 0

New line 12
while counter > 0 and a < unsorted.length

Cool!  It works now.  A guy at my office said I should look up "bubble sorting" to improve this little program.