Re: efficient max() function from sort



On Wed, May 28, 2008 at 5:07 PM, Rob Dixon <rob.dixon@xxxxxxx> wrote:
snip
$max = (sort {$a <=> $b} @z)[-1];
snip

my $max = (sort { $b <=> $a } @z)[0];

is slightly faster than using [-1].

You should only use this form if performance matters and you know that
@z is smaller than 250 items (over 250 items List::Util::max is
faster). In general using List::Util::max (or rolling your own with a
for loop) is preferable to the sort. You know it will take O(n) time,
whereas the sort may take up to O(n*n) time in worst case scenarios
and the average case takes O(n log n) time (but happens to be faster
for small lists due to the fact that sort is written in C).

Of course, if speed matters then you should probably try to find a way
to know max values ahead of time anyway.

--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
.



Relevant Pages

  • Re: sorting K+1 vectors with NlogN comparisons not (K+1)NlogN
    ... using a sorting criteria that looks up elements in the A ... // sort using index sort mechanism as suggested by tom_usenet ... // basically the while-loop in index-shuffle will loop twice. ...
    (comp.lang.cpp)
  • Re: George H.W. Bush will help President Hillary
    ... were attacked by Russia, to toss out an extreme example, would Britain ... opinion swings to the other. ... we're not in any sort of declining position. ...
    (soc.retirement)
  • Re: George H.W. Bush will help President Hillary
    ... were attacked by Russia, to toss out an extreme example, would Britain ... opinion swings to the other. ... This thread started with the defense of the notion that there are some sort ...
    (soc.retirement)
  • Re: An epidemic of cannabis use?
    ... What on *EARTH* gives you the idea that you're in any sort of position ... It's just my opinion. ... bit arrogant sometimes, but then again, I am king of the universe. ...
    (uk.people.support.depression)
  • Re: Review of Art of Assembly Language
    ... None of it is a waste of time. ... >really, it's actually sort of the other way around, in fact... ... Or you could FRY. ...
    (alt.lang.asm)