in reply to Getting the order of an array

my @vector = qw( 27 32 46 5 102 76 ); my @order = sort{ $vector[ $a ] <=> $vector[ $b ] } 0 .. $#vector; print @vector[ @order ]; 5 27 32 46 76 102

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.

Replies are listed 'Best First'.
Re^2: Getting the order of an array
by davidrw (Prior) on May 23, 2005 at 19:30 UTC
    Note that (this is more to OP) the OP said he wanted (or just expected) @order to contain 2,3,4,1,6,5 but in this solution (which i believe is correct) @order contains 3,0,1,2,5,4 ... Note especially the 1-based vs 0-based difference which is necessary for the array slice to work.

      In addition to 1-based, his numbering implied right to left ordering. The 1-based ordering could be accomodated:

      { local $[=1; @order = sort{ $vector[ $a ] <=> $vector[ $b ] } 1 .. $#vector; print @order; } 4 1 2 3 6 5

      though I wouldn't advise it. But accomating the reversal of the natural ordering without requiring sticking in unnecessary reverse calls all over the place was more of a problem.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.