Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How do I do a complex sort on an array?

( #1878=categorized question: print w/ replies, xml ) Need Help??
Contributed by vroom on Jan 08, 2000 at 08:37 UTC
Q&A  > sorting


Answer: How do I do a complex sort on an array?
contributed by vroom

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;
Answer: How do I do a complex sort on an array?
contributed by merlyn

And this is commonly called the Schwartzian Transform, named after me, but not by me.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others perusing the Monastery: (6)
    As of 2014-07-24 03:15 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      My favorite superfluous repetitious redundant duplicative phrase is:









      Results (156 votes), past polls