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

Schwartzian Transform

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

   1: #Want to sort a complex data structure by some element
   2: #efficiently?  For example, how do you sort an array
   3: #of strings by their length?  Use the transform:
   4:    @sorted = map { $_->[1] }
   5:    sort { $a->[0] <=> $b->[0] }
   6:    map { [ length $_, $_ ] } @strings;
   7: 
   8: #Confused?  Put in temporary arrays, 
   9: #just to see what we're doing.
  10: 
  11: # create a temporary array of anonymous arrays
  12: # (0: length of the string, 1: the string)
  13:    @temp = map { [ length $_, $_ ] } @strings;
  14: # sort by length
  15:    @temp = sort { $a->[0] <=> $b->[0] };
  16: # grab just the strings and put them in @ordered
  17:    @sorted = map { $_->[1] } @temp;
  18: 
  19: #Knowing the context of certain operations
  20: # and being able to chain them together
  21: # is crucial to a deep and idiomatic
  22: # understanding of Perl.

Comment on Schwartzian Transform
Download Code
Re: 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
Node Status?
node history
Node Type: perlcraft [id://1394]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (19)
As of 2014-08-29 16:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (282 votes), past polls