Felix Geerinckx wrote:
<snip>
> For small array sizes, it doesn't matter which method you use, since
> the cpu time will be near zero anyway. For larger sizes it does
> matter, and the loop method is a clear winner.
> Therefor, imho, your suggestion in March (and mine now :-) to use a
> loop, is *always* preferable.

*Always* is a very strong word :). For small array sizes the method may make
a difference if you're going to be performing the operation many times.
Sudarshan's banchmark called sort twice and reverse once when it only needed
to call sort once, and it was still much faster than the linear scan for an
array with seven elements. If you had an application that spent most of its
time finding the minimum and maximum element of small collections the sort
method would be preferable. It's also idiomatic (didn't Randall Schwartz
post about this once saying it was an example in the Llama book?) and imho
quite readable.

There are other situations in which you might prefer a log n to a linear
algorithm for this kind of thing. If you need to repeatedly find minimum and
maximum elements of a collection over a period in which insertions and
deletions are being performed you might want to keep the collection sorted.
Likewise if you collect the elements over time and want to amortize the cost
of the operation. If your data is too large to fit in memory a log n
algorithm may beat a linear algorithm badly for all reasonable values of n
if the linear algorithm uses a lot of disk seeks. Without knowing the
details of the application it's not possible to know what algorithm is best.

I suspect that a lot of the people who ask this question are dealing with
small arrays, in which case the sort solution makes sense. It's also kind of
cool :). But the caveat about large arrays _is_ important- don't want people
using it on an array with fifty-million elements! (Of course if you're
trying to maximize performance working with large datasets you might be best
off using C or Lisp anyway, or using an RDBMS to do your heavy lifting- and
hopefully you're not dealing with these kinds of datasets if you're at the
stage where you're first learning how to find the maximum element of an
array).

This (how do I find the greatest/lowest element?) comes up every few months.
Maybe there should be a list faq that covers this and other
questions that get asked a lot and aren't in the Perl faq :).

Tagore Smith



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to