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] };
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.
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.