Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Sorting an array on two computed fields

by TedPride (Priest)
on Dec 16, 2005 at 16:09 UTC ( [id://517280]=note: print w/replies, xml ) Need Help??


in reply to Sorting an array on two computed fields

blazar's solution works properly, unlike some of the other solutions given above (++ for him), but mine is more efficient: 2.08 vs 3.68 seconds for 1000 iterations with 100 randomly generated items. Smaller sets show much the same ratio.
use strict; use warnings; ### Randomly generate numbers my @array; for (0..100) { my @n; push @n, (int rand 15) + 1; for (0..((int rand 3) - 1)) { push @n, int rand 15; } push @array, join '-', @n; } ### Sort the numbers my @arr = map { $_ = join '-', @$_ } sort { mysort($a, $b) } map { $_ = [split '-'] } @array; print join "\n", @arr; ### mysort does the actual comparisons sub mysort { my ($s1, $s2) = ($#{$_[0]}, $#{$_[1]}); for (0..($s1 < $s2 ? $s2 : $s1)) { no warnings; return $_ if $_ = $_[0][$_] <=> $_[1][$_]; } ### N comes before N-0 return ($s1 < $s2 ? -1 : ($s2 > $s1 ? 1 : 0)); }

Replies are listed 'Best First'.
Re^2: Sorting an array on two computed fields
by salva (Canon) on Dec 16, 2005 at 22:01 UTC
    It seems you are ignoring my solution using Sort::Key. On my computer it runs more than 2.5 times faster than yours!
Re^2: Sorting an array on two computed fields
by tphyahoo (Vicar) on Dec 16, 2005 at 18:33 UTC
    Which solutions don't work properly?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://517280]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-19 23:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found