The stupid question is the question not asked PerlMonks

### Complex sorting

by vroom (Pope)
 on Dec 31, 1999 at 22:02 UTC Need Help??

Ever wanted to sort on a computed value or a certain column in a string within an array. It can get pretty tricky to do right. You only want to compute the value you're sorting on once for each array element not every time you do a comparison throughout the sort.

One key function you'll want to know how to use is map. Map allows you to apply a change to a list and get back a new list with the changes.

There are two ways you can use the map function;
```#map BLOCK, LIST
#or something like
@revwords=map{
@letters=split(//);
@revletters=reverse(@letters);
join(' ',@revletters);
} @words;

#or
#map EXPR, LIST
@asciival=map(ord,@letters);
[download]```
The first example takes a list of words and returns a list of each of those words with the letters reversed. This is done by splitting them, then reversing the resulting array, and then returning the joined array which is the word reversed. The second example takes an array of letters and returns a list of their ascii values;

Now say we want to sort an array that contains 3 columns of numbers separated by spaces. We want to sort this array on the sum of these three numbers.

The first thing we want to do is map the original array to an array with the calculated sums, as well as the original values in it.
```@origarray=('0 1 2','0 0 0','-3 -2 -1','10 11 12');
@sortedarray=
map{\$_->[0]}
sort{\$a->[1] <=> \$b->[1]}
map{
my @cols=split(/\s+/);
my \$sum=\$cols[0]+\$cols[1]+\$cols[2];
[\$_,\$sum];
} @origarray;

foreach(@sortedarray){
print "\$_\n";
}
[download]```
We start by doing the basic transform within the innermost map. The current list value comes in as the default variable(\$_), then we split the columns, add them up, and return [\$_, \$sum] which contains the original value followed by the computed value for sorting on. We then sort numerically on this computed value. And then use map so the array only contains the original stuff.

This whole process is known as the Schwartzian Transform.
Here's a template for doing complex sorting
```@sortedarray=
map{\$_->[0]}
# 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
map{
#calculate \$computedsortval
[\$_,\$computedsortval];
} @origarray;
[download]```
This should hopefully give you a better understanding of what is going on when you need to do a complex sort, and hopefully allow you to do it right with very little hassle.

Replies are listed 'Best First'.
Re: Complex sorting
by seacloud (Initiate) on Jul 20, 2004 at 19:01 UTC

Thanks for this tight little tutorial. I'm still trying to wrap my inexperienced head around parts of it. However, in working the first example, I discovered a typo:

You wrote

join(' '),@revletters;
I think it should be
join(' ',@revletters);
(I merely changed the location of the closing parenthesis)

Cheers!

Log In?
 Username: Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perltutorial [id://1641]
help
Chatterbox?
 [karlgoethebier]: ww:My first thought, to be honest... [erix]: and those authors' names don't look like native english speakers. Then again, neither am I :) [karlgoethebier]: but the set of test persons is very small, like in medical studies: "We analyzed 50..."

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (10)
As of 2017-09-25 14:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
During the recent solar eclipse, I:

Results (280 votes). Check out past polls.

Notices?