Db2f60fcc6c2572badac466c4bb6adc5

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?

#!/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 !

60888d58de3bf08cbc0c73e67fd6fd86

Josh N

March 4, 2009, March 04, 2009 01:49, permalink

No rating. Login to rate!

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
A9797da10e2f039c2fe990f2eb56fb72

Fabio

March 9, 2009, March 09, 2009 02:05, permalink

No rating. Login to rate!

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...

D41d8cd98f00b204e9800998ecf8427e

Simon

March 14, 2009, March 14, 2009 23:18, permalink

No rating. Login to rate!

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)

Your refactoring





Format Copy from initial code

or Cancel