in reply to Sorting a two-dimensional array by two columns
The Schwartzian transform is the classic way to do this. First transform your multi-dimensional array to a list of key/reference pairs where the key is some hash of the values you want to sort on (a unique hash is best :) and the reference is a reference to the row the key pertains to. Then sort the pairs by the key. Finally pull the rows out and you're done.
use strict; use warnings; my @chrnums = ( [qw(chr1 10)], [qw(chr3 20)], [qw(chr1 30)], [qw(chr3 5)], [qw(chr5 5)], ); @chrnums = map { #Extract sorted rows $_->[1] } sort {$a->[0] cmp $b->[0]} map { #Transform to keys and refs [(sprintf "%5d%5d", $_->[0] =~ /(\d+)/, $_->[1]), $_] } @chrnums; print "$_->[0] $_->[1]\n" for @chrnums;
Prints:
chr1 10 chr1 30 chr3 5 chr3 20 chr5 5
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sorting a two-dimensional array by two columns
by johngg (Canon) on Jul 05, 2006 at 23:14 UTC | |
by GrandFather (Saint) on Jul 05, 2006 at 23:33 UTC | |
by johngg (Canon) on Jul 09, 2006 at 16:46 UTC | |
|
Re^2: Sorting a two-dimensional array by two columns
by Hue-Bond (Priest) on Jul 05, 2006 at 23:21 UTC | |
by a11 (Novice) on Jul 06, 2006 at 08:33 UTC |