Discussion:
Sort 2-d array using multiple columns
(too old to reply)
scottmf
2005-07-20 23:13:55 UTC
Permalink
I have an array similar to the following (the one I am actually sorting
has 25 columns and several thousand rows):

@AoA = ([3, 1, 8],
[2, 2, 6],
[2, 1, 4],
[3, 2, 3]);

and I need to sort it by the second column, then the first column so
that my output would be as follows:

@sorted = ([2, 1, 4],
[3, 1, 8],
[2, 2, 3],
[3, 2, 6]);

I can sort by one column without a problem but have not been able to
find anything on sorting with respect to both columns. Any help would
be much appreciated.
Jim Gibson
2005-07-21 00:15:43 UTC
Permalink
Post by scottmf
I have an array similar to the following (the one I am actually sorting
@AoA = ([3, 1, 8],
[2, 2, 6],
[2, 1, 4],
[3, 2, 3]);
and I need to sort it by the second column, then the first column so
@sorted = ([2, 1, 4],
[3, 1, 8],
[2, 2, 3],
[3, 2, 6]);
I can sort by one column without a problem but have not been able to
find anything on sorting with respect to both columns. Any help would
be much appreciated.
Ignoring the fact that your third columns got mixed up during your
manual sort, this should give you what you want:

@sorted = sort { $a->[1] <=> $b->[1] || $a->[0] <=> $b->[0] } @AoA;


----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
scottmf
2005-07-21 00:41:42 UTC
Permalink
Thanks, it works perfectly.

~Scott
Gunnar Hjalmarsson
2005-07-21 00:42:38 UTC
Permalink
... have not been able to find anything on sorting with respect
to both columns. ...
Where did you look then?? "perldoc -f sort" includes examples with a
second sort criterium.
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
Tad McClellan
2005-07-21 03:33:40 UTC
Permalink
Post by scottmf
@AoA = ([3, 1, 8],
[2, 2, 6],
[2, 1, 4],
[3, 2, 3]);
and I need to sort it by the second column, then the first column
have not been able to
find anything on sorting with respect to both columns.
You are expected to check the Perl FAQ *before* posting to
the Perl newsgroup.
Post by scottmf
Any help would
be much appreciated.
You already have the help you need sitting on your hard disk, no
need to ask thousands of people around the world to take the
time to help you.


perldoc -q sort

How do I sort an array by (anything)?

...
If you need to sort on several fields, the following paradigm
is useful.

@sorted = sort { ...
--
Tad McClellan SGML consulting
***@augustmail.com Perl programming
Fort Worth, Texas
Loading...