Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: assigning the maximum of two numbers

by QM (Parson)
on Nov 03, 2005 at 19:06 UTC ( [id://505479]=note: print w/replies, xml ) Need Help??


in reply to assigning the maximum of two numbers

sub assignmax5 { @a = sort@_; pop @a; }
I prefer this, especially for large arrays:
sub assignmax5 { return (sort @_)[-1]; }
It's immediately obvious, and easy to maintain.

Update: strike

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^2: assigning the maximum of two numbers
by Roy Johnson (Monsignor) on Nov 03, 2005 at 19:10 UTC
    But sort doesn't scale well, like List::Util 'max' does. So "especially for large arrays", you should not use sort to find the maximum.

    Caution: Contents may have been coded under pressure.
Re^2: assigning the maximum of two numbers
by Tanktalus (Canon) on Nov 03, 2005 at 19:25 UTC

    Especially for large arrays? Wouldn't this be an O(nlogn) function? I mean, if you wanted an arbitrary number of the maximum numbers in a list, sure, you're pretty much already sorting. But for just the top 1, you should use an O(n) algorithm, which gets even more important for "large arrays".

    For short arrays, the difference between sort and looping with a ternary will be minor. For long arrays, well, it becomes a bit more important.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-26 06:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found