Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Array sort - kind of...

by wog (Curate)
on Feb 04, 2002 at 00:57 UTC ( #143135=note: print w/replies, xml ) Need Help??

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.


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

      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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://143135]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2022-10-07 06:58 GMT
Find Nodes?
    Voting Booth?
    My preferred way to holiday/vacation is:

    Results (29 votes). Check out past polls.