You should never resort to sorting to find the max or min value of a list unless the side effect of sorting has a benefit later on.
Thanks so much for those valuable insights. I am intrigued with your statement above. I wonder why it is so?
Because sort has to find the order of all the elements, not just find the largest one. So if you've got 1000 items, it's spending all its time putting the 999 you don't care about in the right order. (Actually, it takes O(n log n) to sort a list, but only O(n) to find the maximal element using a simple scan.)
... when possible, uses a C implementation that makes it really fast
I thought the built in sort function "is" implememented under "C" already? right?
Well, yes, but if you specify a block to sort by, it has to go back into perl to call that on every pair of elements. IIRC, there are a few blocks that have been hardcoded ({$a <=> $b}, $b cmp $a, etc), but if all you care about is a single value, there's no point in sorting everything to get it.
| [reply] [d/l] [select] |
neversaint,
Eimi Metamorphoumai has already done a great job of answering your question. I just wanted to try and make something clear as I made the poor mistake of assuming something would be obvious.
Using a water mark algorithm is the best way of finding a max/min value in an unsorted list. List::Util provides such an algorithm that uses a C implementation when and where possible. This isn't comparing apples and apples since both are in C. One is doing far less work (as was pointed out by Eimi Metamorphoumai). So unless you need the values sorted for some other reason later on, don't use sort for this.
| [reply] |