Hi,

I’m working through the Learning To Program book(2nd edition) and am

stuck on the sort/recursion exercise (page 93/94). The exercise is to

roll your own sort method for use on an array. The suggestions are to

create an additional two arrays; 1) for the sorted words 2) another

for the unsorted words, take the list of words, find the smallest, and

put it on the end of the already-sorted list. The remaining items go on

the

unsorted. The idea being to recurse through the list of unsorted words

adding elements to the sorted list until done.

There are several routes I could take to get closer but I’m trying to

stay within the constraints of the book. That means I can use .each,

.push, .pop, .length, .join, and .last. Hopefully I’m not leaving

anything out. Certainly I could use the .sort method and I could look

at the answer in the book but the idea is creating my own for the

experience. But I’m stuck. I’m hoping for a nudge in the right

direction instead of someone telling me outright

how to do it.

In English what I think I need to do is take each element of the array

and compare it to the rest of the elements and if it’s the smallest,

push it onto the sorted list and push the remaining elements onto the

unsorted. Then call the method again with the sorted and unsorted

lists. That’s the recursion part.

I guess the problem I’m having is knowing how to check each element of

the unsorted array against the other elements. I can check if the

current element is smaller than the other elements using < (less than)

but that doesn’t mean it’s the smallest in the whole array. So I would

only want to

push it onto sorted array if it’s smaller than everything else.

This is about as far as I can get and it’s not close to working. Plus

it seems like a mess to me.

#!/usr/bin/ruby

def sort some_array

recursive_sort some_array, []

end

def recursive_sort unsorted_array, sorted_array

until 0 == unsorted_array[unsorted_array.length]

unsorted_array.each do |outer|

unsorted_array.each do |inner|

if outer < inner

sorted_array.push(outer)

else

unsorted_array.push(inner)

end

end

end

end

puts sorted_array

recursive_sort unsorted_array, sorted_array

end

a = [‘c’, ‘b’, ‘a’, ‘d’]

sort(a)

Any hints welcome.

Thank-you.