Welcome to the Monastery PerlMonks

Schwartzian Transform

by chromatic (Archbishop)
 on Dec 25, 1999 at 09:21 UTC 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.```

Replies are listed 'Best First'.
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];

Create A New User
Node Status?
node history
Node Type: perlcraft [id://1394]
Approved by root
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2018-03-25 03:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I think of a mole I think of:

Results (300 votes). Check out past polls.

Notices?