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 <unsort[0]
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/.