How to sort array ascending, except zero ?

B

brabuhr

Am Montag 08 Juni 2009 20:55:17 schrieb (e-mail address removed):

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,078
Latest member
MakersCBDBlood

Latest Threads

Top