A place for my personal musings, about programming, design or whatever come across my mind

A slightly better sort

Finally have the time to come back to the sorting exercise, here is a slightly better version of sort.
It still doesn’t take care of duplicate elements, but compare to the first sorting version, this one is shorter, as the whole finding smallest element left in the array is now done by inject and a ternary operator, a whole 7 lines of code cut to just 1. And now it no longer sort animals, it sort a list of hackers

hackers = %w{matz ddh adrian guido gosling knuth linus}
i = hackers.length 
sorted = []
while i > 0
  small = hackers.inject{ |a,b| a < b ? a : b}
  sorted.push small 
  hackers.delete small
  i -= 1
end
p sorted

And the result of the sort is

["adrian", "ddh", "gosling", "guido", "knuth", "linus", "matz"]

So the next iteration will be to take care of duplicated elements…stay tuned.

Leave A Comment