No such thing as a small change PerlMonks

### Answer: How can I find the index of the biggest element in an array?

by Skeeve (Vicar)
 on May 27, 2007 at 18:57 UTC Need Help??

Q&A > arrays > How can I find the index of the biggest element in an array? - Answer contributed by Skeeve

```my \$i = \$#data;
my \$max = \$i;
\$max = \$data[\$i] > \$data[\$max] ? \$i : \$max while \$i--;
print "Max value is \$data[\$max], at index \$max\n"
[download]```

• Comment on Answer: How can I find the index of the biggest element in an array?
• Download Code
Replies are listed 'Best First'.
Re: Answer: How can I find the index of the biggest element in an array?
by Jenda (Abbot) on May 28, 2007 at 14:09 UTC

I don't think it's good to scare people with a ternary operator and statement modifier in one statement. I do think

```while (\$i--) {
\$max = \$i if \$data[\$i] > \$data[\$max];
}
[download]```
would be much more readable. I'd probably write it like this though:
```my \$max = 0;
for (0 .. \$#data) {
\$max = \$_ if \$data[\$_] > \$data[\$max]
}
[download]```

Update (suggested by ysth): It's actually better to start looping at index 1:

```my \$max = 0;
for (1 .. \$#data) {
\$max = \$_ if \$data[\$_] > \$data[\$max]
}
[download]```
There's no point in comparing the first element to itself.

Re: Answer: How can I find the index of the biggest element in an array?
by Skeeve (Vicar) on May 27, 2007 at 19:40 UTC

Oops! Little Problem! Replace "scalar @data" with "\$#data"

Update: Fixed by jdporter deletion of this node is okay with me...

s\$\$([},&%#}/&/]+}%&{})*;#\$&&s&&\$^X.(\$'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`\$''`"e
Log In?
 Username: Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2017-08-17 13:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (288 votes). Check out past polls.

Notices?