http://qs321.pair.com?node_id=143135


in reply to Array sort - kind of...

@array = sort { $a->[2] <=> $b->[2] } @array

But, you say you want to find the $i with the smallest z value. It's best to _not_ sort for that:

my $min_i = 0; foreach my $i (1..$#array) { $min_i = $i if $array[$i]->[2] < $array[$min_i]->[2]; }

(update: Oops. Forgot the ->[2].)

This should be signifigantly faster, especially when @array gets large...

Replies are listed 'Best First'.
Re: Re: Array sort - kind of...
by Anonymous Monk on Feb 04, 2002 at 02:07 UTC
    This isn't relevant at all for the issue, but I have a question: Why do you choose to have $i over $_? There is a slight performance improvement when the loop is entered, but still...
      True, he could have it written it in such a way to minimize a bunch of the minor overheads of the loop construct.

      Thus

      my $min_i = 0; foreach my $i (1..$#array) { $min_i = $i if $array[$i]->[2] < $array[$min_i]->[2]; }
      becomes
      my $index=0; $array[$_][2]<$array[$index][2] && ($index=$_) foreach 1..$#array;
      But I'm so sure its easier to understand...

      ;-)

      Yves / DeMerphq
      --
      When to use Prototypes?

        Wouldn't this eliminate more of the overhead?
        my ($min, $min_i) = ($array[0]->[2], 0); foreach my $i (1..$#array) { ($min, $min_i) = ($array[$i]->[2], $i) if $array[$i]->[2] < $min; }


          p
      I find it clearer, since smitz referred to $i as the index to the array in the question and since $i, $j, etc. make me think "this is a counter variable" when I see them.