Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: How do I do a complex sort on an array?

by vroom (His Eminence)
on Jan 18, 2000 at 23:23 UTC ( [id://2149]=note: print w/replies, xml ) Need Help??


in reply to How do I do a complex sort on an array?

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;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-23 10:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found