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] };
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.
Perl has a built-in sort() function to sort an array of alphabets and numbers. When an array is passed to the sort() function it returns a sorted array. Sorting of Arrays in Perl can be done in multiple ways: Use of ASCII values to sort an Array.
Perl has a built-in function called sort that can, unsurprisingly, sort an array. In its most simple form, you just give it an array, and it returns the elements of that array in a sorted order. @sorted = sort @original.
sort() function in Perl is used to sort a list with or without the use of method of sorting. This method can be specified by the user in the form of subroutines or blocks. If a subroutine or block is not specified then it will follow the default method of sorting.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With