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

Let's say I have an array @a = (7,3,8);What's the best way to sort it by the values, but output the corresponding index of the unsorted array? For this example, the output should be an array with elements, in order 1,0,2.

Replies are listed 'Best First'.
Re: Sorting Arrays
by merlyn (Sage) on Jan 08, 2002 at 21:43 UTC
      thank you very much. But why does this work??
        my @indicies = sort { $a[$a] <=> $a[$b] } 0..$#a;

        merlyn is sorting a list of integers (0..$#a) corresponding to the indices of the elements of your array @a. Recall that within sort code blocks, $a and $b are special variables representing the two variables to be ordered each time the block is evaluated. So here,  $a[$a] <=> $a[$b] means sort the indices of the array by the contents of its elements.

        It's a bit confusing in this case because of the use of @a as your array variable and the use of $a and $b as special variables to sort.

        HTH,

        Josh
Re: Sorting Arrays
by Masem (Monsignor) on Jan 08, 2002 at 21:49 UTC
    You can use a modified Schwartizan transformation for that:
    my $i = 0; my @sorted_indicies = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ $_, $i++ ] } @array; # OR my @sorted_indicies = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ $array[$_], $_ ] } (0..$#array);
    (The first requires the extra varaible, while the second requires you use the array variable twice.)

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important

      If you'll grant me an audience knowing that I know a bit about the Schwartzian Transform... {grin}

      The ST makes sense only when the orderingfunction on each element to be sorted is expensive to compute, and should therefore be cached to prevent multiple calls (so the list has to be long enough as well). Since "array lookup" is a cheap (nearly free) orderingfunction, the ST is far too much overkill on this choice.

      -- Randal L. Schwartz, Perl hacker