good chemistry is complicated,and a little bit messy -LW PerlMonks

### Re: largest number inside array/hash

by DigitalKitty (Parson)
 on Apr 06, 2004 at 21:47 UTC ( #343134=note: print w/replies, xml ) Need Help??

in reply to largest number inside array/hash

Hi Anonymous Monk.

In an attempt to display the 'syntactically rich' nature of the perl language, I have taken the liberty of including yet another array oriented solution:
```#!/usr/bin/perl -w
use strict;

my @array = ( 33, 56, 3, 2, 67, 101, 218, 4, 17 );
my @nums = sort { \$a <=> \$b } @array;

print "The largest number is: \$nums[\$#nums]\n";

Output:
```C:\>perl pg8.pl
The largest number is: 218

C:\>

Hope this helps,
-Katie

Replies are listed 'Best First'.
Re: Re: largest number inside array/hash
by TomDLux (Vicar) on Apr 07, 2004 at 07:35 UTC

Think back to second year of college, when you took that Algorithms course.

A good sort such as quick sort is O( N logN ), poor ones such as bubble sort are O( N^2 ). A max() function requires a single pass through the list, and so is O( N ). It would be silly to do N log N - N ( i.e. N (log N - 1) ) operations more than you need to.

--
TTTATCGGTCGTTATATAGATGTTTGCA

In practice, on small data sets, the penalty is a factor of 10 or so. Which is similar to the penalty from using Perl. If you can get a good constant, the log(n) might be paid for. (Real example. Wavelet algorithms tend to be O(n) while the FFT is O(n*log(n)). But the FFT has a better constant.) At some point worrying about how the computer spends a millisecond of time itself becomes silly.

Me, I tend to treat logarithmic factors as noise unless I'm trying to squeeze performance. The difference between linear and quadratic I care about. O(n) vs O(n*log(n)) I don't. I know them, I just don't care much.

Re^2: largest number inside array/hash
by Anonymous Monk on Aug 17, 2012 at 17:09 UTC
Hi Nice elegant solution. but i guess this would work too
```#!/usr/bin/perl -w

use strict;

my @array = ( 33, 56, 3, 2, 67, 101, 218, 4, 17 );

my @nums = sort { \$b <=> \$a } @array;

print "The largest number is: \$nums[0]\n";

Create A New User
Node Status?
node history
Node Type: note [id://343134]
help
Chatterbox?
 [Discipulus]: a solution would be disabiltate sig as default and let users to show them [karlgoethebier]: now it's getting weird... [GotToBTru]: 'getting'? [Discipulus]: why karlgoethebier ? [GotToBTru]: ugh .. what's the term for comparing versions of an algorithm to determine which is most efficient?

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (16)
As of 2017-06-22 12:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How many monitors do you use while coding?

Results (519 votes). Check out past polls.