Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Efficient sorting using the Schwartzian Transform

by chromatic (Archbishop)
on Dec 25, 1999 at 09:21 UTC ( [id://1394]=CUFP: print w/replies, xml ) Need Help??

Want to sort a complex data structure by some element efficiently?
For example, how do you sort an array of strings by their length?
Use the transform:
@sorted = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ length $_, $_ ] } @strings;
Confused? Put in temporary arrays, just to see what we're doing.

create a temporary array of anonymous arrays
(0: length of the string, 1: the string)

@temp = map { [ length $_, $_ ] } @strings;
sort by length
@temp = sort { $a->[0] <=> $b->[0] };
grab just the strings and put them in @sorted
@sorted = map { $_->[1] } @temp;
Knowing the context of certain operationsand being able to chain them together is crucial to a deep and idiomatic understanding of Perl.

Replies are listed 'Best First'.
Re: Efficient sorting using the Schwartzian Transform
by I0 (Priest) on Jan 02, 2001 at 18:06 UTC
    You probably meant @temp = sort { $a->[0] <=> $b->[0] } @temp;

    Although, given a @temp array, it benchmarks faster to do
    @temp = map { length $_ } @strings; @sorted = @strings[sort{$temp[$a]<=>$temp[$b]} $[..$#temp];

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2026-05-14 03:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.