From: Jeff de Vries Date: 2006-04-30T07:35:10+09:00 Subject: Re: Learn to Program, by Chris Pine Restricting to what is covered in chapters 1-10, how about the following? def sort some_array recursive_sort some_array, [] end def recursive_sort unsorted_array, sorted_array if unsorted_array.size == 0 return sorted_array else smallest = unsorted_array[0] unsorted_array.each do |x| if x < smallest smallest = x end end new_unsorted_array = [] unsorted_array.each do |x| if x == smallest sorted_array.push(x) else new_unsorted_array.push(x) end end recursive_sort new_unsorted_array, sorted_array end end On Apr 29, 2006, at 11:38 AM, Colin wrote: > > Hello, > > thank you very much for all these good answers > (especially to Jan_K and Dave Burt ). > > Im learning ruby with the same book and get stuck > in chapter 10.2 Rite of Passage:Sorting > this exercise is about array sort algorithms. > Instead of 'array.sort' i have to program my own sort method. > > chris pine gives a few hints: > using < to find the smallest word in a list > > take two lists in the method > > and these two empty methods > > def sort some_array > recursive_sort some_array, [] > > end > > def recursive_sort unsorted_array, sorted_array > > end > > > After a lot of trying and searching ... > > ...I found the quicksort algorithm and this code > > def quicksort( array ) > if array.size <= 1 > array > else > ls, rest = array.partition { |i| i < array[0] } > puts 'ls:'+ls.to_s > puts 'rest:'+rest.to_s > rs, rest = rest.partition { |i| i > array[0] } > puts 'rs:'+rs.to_s > puts 'rest2:'+rest.to_s > quicksort( ls ) + rest + quicksort( rs ) > > > end > end > > Yes this is a possible solution, but array.partion ,double > assignments(ls,rest) > of variables,arrays and the 'short block' (like { |i| i > array[0] }) > are not mentioned in any chapter before. > > Although I understand the Code above , I'm looking for an easy > solution > that don't leave the scope of chaper 1 to 10 . > > Here's my own code, but it doesn't work . > > > def ownsort unsort, sort > rest=[] > rs=[] > if unsort.size <= 1 > unsort > else > unsort.each do |i| > if i > sort.push i > else > rest.push i > end > end > > end > rest > end > > > thanks for reading and hopefully some hints... > > colin > > > -- > Posted via http://www.ruby-forum.com/. >