Mike
Mike

Reputation: 1319

Perl: Sorting 2D array with multiple columns based on a particular column

Pseudo code:

my @unsortedArray = { ["Harry", 10], ["Tim", 8], ["Joe", 3]};
my @sortedArray = ?????

Final sortedArray should be sorted based on col-2 (integers), taking care of the 1-to-1 relationship with the "Name of the person" (col-1). Final result should look like:

sortedArray should be { ["Joe", 3], ["Tim", 8], ["Harry", 10] }; 

Upvotes: 5

Views: 11762

Answers (2)

LeoNerd
LeoNerd

Reputation: 8532

A more efficient solution, especially for larger arrays, may be to use List::UtilsBy::nsort_by:

use List::UtilsBy qw( nsort_by );

my @unsorted = ( ["Harry", 10], ["Tim", 8], ["Joe", 3] );

my @sorted = nsort_by { $_->[1] } @unsorted;

While in small cases the overhead is not likely to be noticed, for more complex functions the O(n log n) key extraction cost becomes higher, and it is more preferrable to extract the "sort key" of each value only once, which is what nsort_by does.

Upvotes: 2

Stefan Majewsky
Stefan Majewsky

Reputation: 5555

You can give a predicate to sort, that is: a function which is evaluated to compare elements of the list.

my @unsorted = ( ["Harry", 10], ["Tim", 8], ["Joe", 3] );

my @sorted = sort { $a->[1] <=> $b->[1] } @unsorted;

In the predicate (the expression in curly braces), $a and $b are the elements of the outer list which are compared.

sort is only concerned with one-dimensional lists, so it won't mess with the internal structure of the elements of the outer list. So the relationship between name and number is retained effortlessly.

Refer to perldoc -f sort and perldoc perlop for more details.

Upvotes: 8

Related Questions