Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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...


Comment on Re: Array sort - kind of...
Select or Download Code
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...
      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.
      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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2014-04-19 19:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls