#!/usr/bin/env ruby -wKU
def array_sort some_array
temp_array = Array.new
while not some_array.empty? do
j = ""
some_array.each do |i|
j = i if j.downcase < i.downcase
end
temp_array.push j
some_array.delete j
end
temp_array.reverse!
return temp_array
end
array_to_sort = %w[ZERO silly CHILL Chill chill school one time here in the city]
puts array_sort(array_to_sort)
Refactorings
No refactoring yet !
Josh N
March 4, 2009, March 04, 2009 01:49, permalink
u can use quicksort
class Array
def quicksort
return self if length <= 1
pivot = shift
less, greater = partition {|x| x <= pivot}
less.quicksort + [pivot] + greater.quicksort
end
end
puts [8,99,4,1000,1,2,3,100,5,6].quicksort.join(',')
from: http://joshnuss.blogspot.com/2008/12/quicksort.html
Fabio
March 9, 2009, March 09, 2009 02:05, permalink
but if you really want quicksort to be quick, first of all you need to do it iteratively and not recursively!
Anyway, for you code instead of using the reverse! at the end of the cycle, you should just use unshift instead of push...
Simon
March 14, 2009, March 14, 2009 23:18, permalink
Depending on how much you want to use from Enumerable and Array you can squeeze this until there is virtually no code left.
#!/usr/bin/env ruby -wKU
def array_sort some_array
(0...some_array.size).each do |i|
j = some_array[i..-1].max {|a, b| a.downcase <=> b.downcase}
some_array.unshift(some_array.delete j)
end
some_array
end
array_to_sort = %w[ZERO silly CHILL Chill chill school one time here in the city]
puts array_sort(array_to_sort)
With the existance of the sort and sort! methods the code below is useless. But since I'm learning I've written my own sort routine. It's not very pretty, but it does work. How can I make this more Ruby-like without using the built-in sort method?