Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Array sort - kind of...

by smitz (Chaplain)
on Feb 04, 2002 at 00:51 UTC ( [id://143134]=perlquestion: print w/replies, xml ) Need Help??

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

Noble Monks:
I've just completed my 1st real program that actually achieves something, and damn it feels good. One part of this script, though, contains an array of arrays, like so:

$array[$i] = [x, y, z];

This array needs to be sorted in order to find the $i with the smallest z value. Not too hard, and I did myself.
The problem lies with this website. Since coming here I have seen code so short, efficient, beautifull, etc. that I get quite a minority complex. When I look at the way I sort my array, I just dont like it. Its, well, amateurish. I know this is a simple problem which I have solved, but I would like to see how a real monk would do it.

Thanks for your time,
SMiTZ

Replies are listed 'Best First'.
Re: Array sort - kind of...
by wog (Curate) on Feb 04, 2002 at 00:57 UTC

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

      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?

        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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://143134]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2024-04-23 09:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found