From: Robert Klemme Date: 2009-06-08T18:27:39+09:00 Subject: Re: How to sort array ascending, except zero ? 2009/6/8 Martin DeMello : > On Mon, Jun 8, 2009 at 2:10 PM, Paganoni wrote: >> Hello, I need to sort >> [1,4,2,0,8,9] to [1,2,4,8,9,0] >> >> A simple ascending sort but with the zero values to the end > > max = a.max + 1 > # or max = 2 ** 31, say, if you don't want the extra pass > # but sorting is O(n log n) and max is O(n) so it doesn't really matter Still traversing the array twice just to get the max beforehand does not /feel/ right. I'd rather use your "large constant" - maybe even with a _really_ large number: :-) irb(main):020:0> a = [1,4,2,0,8,9] => [1, 4, 2, 0, 8, 9] irb(main):021:0> INF = 1.0 / 0.0 => Infinity irb(main):022:0> a.sort_by {|x| x == 0 ? INF : x} => [1, 2, 4, 8, 9, 0] Another good alternative is to use the block form of #sort: irb(main):023:0> a.sort do |x,y| irb(main):024:1* case irb(main):025:2* when x == 0 then 1 irb(main):026:2> when y == 0 then -1 irb(main):027:2> else x <=> y irb(main):028:2> end irb(main):029:1> end => [1, 2, 4, 8, 9, 0] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/