Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

How do I do a complex sort on an array?

by vroom (Pope)
on Jan 08, 2000 at 08:37 UTC ( #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!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            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?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others meditating upon the Monastery: (7)
    As of 2018-07-23 16:12 GMT
    Find Nodes?
      Voting Booth?
      It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

      Results (472 votes). Check out past polls.