Search code examples
arraysperlsortingdata-structuresperl-data-structures

sort an array according to elements of a second array


Suppose I have two arrays that look like this:

('1', '6', '8', '4', '5')
('a', 'c', 'd', 'f', 'w')

I want to sort the first array, and the order of elements in the second array should change in the same way as the first array, so the order of the two becomes as follows:

('1', '4', '5', '6', '8')
('a', 'f', 'w', 'c', 'd')

Any ideas of how to do that in Perl?


Solution

  • You need to sort the indices into the array. Like this

    use strict;
    use warnings;
    
    my @aa = qw/ 1 6 8 4 5 /;
    my @bb = qw/ a c d f w /;
    
    my @idx = sort { $aa[$a] <=> $aa[$b] } 0 .. $#aa;
    
    @aa = @aa[@idx];
    @bb = @bb[@idx];
    
    print "@aa\n";
    print "@bb\n";
    

    output

    1 4 5 6 8
    a f w c d