##################################
### WARNING:  Spoilers follow! ###
##################################

On Jun 29, 2006, at 4:09 PM, Dark Ambient wrote:

> On 6/29/06, James Edward Gray II <james / grayproductions.net> wrote:
>> 2.  If you want to press on, see if this description of the problem
>> makes a little more sense:  One way to sort an Array is to constantly
>> move the lowest element out of it, and into a result Array.  If you
>> do this for all elements in the Array, you sort it.  For example:
>
> My biggest problem was that in my mind one had to solve the problem
> using the tools covered in the book.  Judging from the other examples
> others here were kind to offer up, I don't feel that there was enough
> in the previous chapters to arm , at least myself, with the tools to
> implement the sort.

We're going to know better ways because we know more of the  
language.  Don't doubt what you have learned though!  Chris is  
carefully feeding you the key tools and they can be used to do just  
about anything, with enough effort.

Here's a solution I'm pretty sure only uses what you have learned up  
to chapter 10:

#!/usr/local/bin/ruby -w

def sort(array)
   recursive_sort(array, [])
end

def recursive_sort(unsorted, sorted)
   # find the lowest element
   lowest = nil
   unsorted.each do |item|
     if lowest == nil || item < lowest
       lowest = item
     end
   end

   # add it to our sorted list
   sorted.push(lowest)

   # make a new unsorted list, minus the low guy
   new_unsorted = [ ]
   added        = false
   unsorted.each do |item|
     if added == false and item == lowest
       added = true
     else
       new_unsorted.push(item)
     end
   end

   # return sorted list if we are done, or recurse to keep sorting
   if new_unsorted.size == 0
     sorted
   else
     recursive_sort(new_unsorted, sorted)
   end
end

list = ['zeta', 'beta', 'alpha', 'beta']
puts sort(list)

__END__

Hope that helps.

James Edward Gray II