Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

How do I do a complex sort on an array?

by vroom (His Eminence)
on Jan 08, 2000 at 08:37 UTC ( [id://1878]=perlquestion: print w/replies, xml ) Need Help??

vroom has asked for the wisdom of the Perl Monks concerning the following question: (sorting)

How do I do a complex sort on an array?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I do a complex sort on an array?
by vroom (His Eminence) on Jan 18, 2000 at 23:23 UTC
    Basically what you do is make an array of references to arrays with two elements. The first element is your element in your original array, the second element is the value you compute to sort on. Note we only do this once not every time we do a comparison in the sort. This will result in a huge time savings in sorting a large array. Next we sort on this computed value. Then we return an array containing only the original elements.
    @sortedarray= map{$_->[0]} # return an array that only contains the original value +s (now sorted) # sort on $computedsortval # you use only use one of these sort lines sort{$a->[1] <=> $b->[1]} # this one for numerical sorting sort{$a->[1] cmp $b->[1]} # this one for textual sorting #this map block computes the value you're going to sort on #and places it in $computedsortval map{ #calculate $computedsortval [$_,$computedsortval]; } @origarray;
Re: How do I do a complex sort on an array?
by merlyn (Sage) on Apr 26, 2000 at 03:23 UTC
    And this is commonly called the Schwartzian Transform, named after me, but not by me.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-03-19 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found