rahulm has asked for the wisdom of the Perl Monks concerning the following question:

there are two perl arrays ,suppose @a={1,5,3} @b={5,2,1} the numbers in b are related to a as priority - > Id concept as in the PRIORITY OF ID 3 in array a is no 1 in array b, now i got how to sort array b using @b = sort ({$a <=> $b}@b); in ascending order now @b={1,2,5} what i want to arrange the correspoding ID in a in parallel to b as in array a should be @a={3,5,1} please guide regarding this ,looking forward for a favorable response from your side

Replies are listed 'Best First'.
Re: sorting of two perl arrays
by ikegami (Patriarch) on Oct 30, 2008 at 19:43 UTC
    When dealing with parallel arrays, the bond between them is the indexes. That means you need to sort the indexes.
    my @eles = ( 1, 5, 3 ); my @prios = ( 5, 2, 1 ); my @idxes = sort { $prios[$a] <=> $prios[$b] } 0..$#eles; @eles = @eles [ @idxes ]; @prios = @prios[ @idxes ]; print(join(', ', @eles), "\n");
Re: sorting of two perl arrays
by BrowserUk (Patriarch) on Oct 30, 2008 at 19:45 UTC

    Create an array of indices sorted by @b and then use it to reorder both arrays:

    @a = (1,5,3);; @b = (5,2,1);; @sortedIndices = sort{ $b[ $a ] <=> $b[ $b ] } 0 .. $#b;; @a = @a[ @sortedIndices ];; @b = @b[ @sortedIndices ];; print "@a\n@b";; 3 5 1 1 2 5

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: sorting of two perl arrays
by ccn (Vicar) on Oct 30, 2008 at 19:52 UTC

    Consider to choose another data representation.
    You can tie numbers and priorities in some ways

    # as array of arrays my @data_aoa = ( [1, 5], # [number, priority] [5, 2], [3, 1] ); # or more verbose as array of hashes my @data_aoh = ( {number => 1, pri => 5 }, {number => 5, pri => 2 }, {number => 3, pri => 1 } ); # now sort by priority my @sorted_aoa = sort { $a->[1] <=> $b->[1] } @data_aoa; my @sorted_aoh = sort { $a->{pri} <=> $b->{pri} } @data_aoh;
Re: sorting of two perl arrays
by Narveson (Chaplain) on Oct 30, 2008 at 20:51 UTC

    Do your array indices matter to you? Probably not. Perl lets you ignore them.

    What matters is that each item in @b is the PRIORITY OF the item in @a. To remember this, use a hash.

    my %priority_of; @priority_of{@a} = @b; my @a_sorted_by_priority = sort { $priority_of{$a} <=> $priority_of{$b} } @a;

    Efficiency experts may shudder at the hash lookups inside the sort block, but I say clarity first. Perl code can express what you care about. At a later stage it can be optimized.

    Speaking of clarity, the names @a and @b don't really express what you are thinking about. I have replaced @b with %priority_of. What kind of thing is listed in @a?