# How to sort array ascending, except zero?

On 08.06.2009 22:42, [email protected] wrote:

On Mon, Jun 8, 2009 at 4:08 PM, Sebastian
Hungerecker[email protected] wrote:

Am Montag 08 Juni 2009 20:55:17 schrieb [email protected]:

Assuming a stable sorting algorithm
Neither sort nor sort_by use a stable sorting algorithm though.

But, at least it was pretty fast even if it was not correct.

Hehe, talk about priorities.

Cheers

robert

On Mon, Jun 8, 2009 at 4:08 PM, Sebastian
Hungerecker[email protected] wrote:

Am Montag 08 Juni 2009 20:55:17 schrieb [email protected]:

Assuming a stable sorting algorithm

Neither sort nor sort_by use a stable sorting algorithm though.

But, at least it was pretty fast even if it was not correct.

require βbenchmarkβ
Infinity = 1.0/0.0
Benchmark.bm(25) do |b|
a = (1β¦500000).map{|n| rand(10) - 20}
b.report(βAβ) {
a.sort.sort_by{|n| n.zero? ? 1 : 0}
}
b.report(βDβ) {
tmp = a.partition{|x| x != 0 }
tmp[0].sort + tmp[1]
}
b.report(βFβ) {
n = 0
a.sort_by{|x| n+= 1; [x, n]}.sort_by{|n| n.zero? ? 1 : 0}
}
b.report(βGβ) {
tmp = a.sort.partition{|x| x != 0 }
tmp[0] + tmp[1]
}
b.report(βHβ) {
tmp = a.sort.select{|x| x != 0 }
tmp + ([0] * (a.size - tmp.size))
}
end

ruby1.8 /tmp/z
user system total real
A 1.030000 0.160000 1.190000 ( 1.313981)
D 0.720000 0.170000 0.890000 ( 0.996888)
F 19.510000 1.270000 20.780000 ( 24.233460)
G 0.800000 0.170000 0.970000 ( 1.180949)
H 0.540000 0.140000 0.680000 ( 0.897509)

ruby1.9 /tmp/z
user system total real
A 0.440000 0.020000 0.460000 ( 0.520912)
D 0.250000 0.000000 0.250000 ( 0.274845)
F 17.720000 0.080000 17.800000 ( 19.969714)
G 0.260000 0.000000 0.260000 ( 0.299049)
H 0.180000 0.000000 0.180000 ( 0.210772)

jruby /tmp/z
user system total real
A 1.688000 0.000000 1.688000 ( 1.641000)
D 0.848000 0.000000 0.848000 ( 0.849000)
F 13.181000 0.000000 13.181000 ( 13.180000)
G 0.678000 0.000000 0.678000 ( 0.678000)
H 0.591000 0.000000 0.591000 ( 0.591000)

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

I really donβt see how to do

Thanks for your help

Delegate the FixNum class

http://www.pastie.org/505312

2009/6/9 Rha7 [email protected]:

Delegate the FixNum class

http://www.pastie.org/505312

Another good idea! However, you can save yourself a bit of typing:

http://www.pastie.org/505471

Kind regards

robert