3 ms·
> For instance, it's possible to mathematically prove in some cases that one algorithm is better than another; a set of ten nested for loops simply has greater
by pjscott 16y ago
> For instance, it's possible to mathematically prove in some cases that one algorithm is better than another; a set of ten nested for loops simply has greater time complexity than one. You don't need to actually test which algorithm is better.
At the risk of being pedantic, I want to point out that it's not always so clear-cut. Take sorting, for example. Everybody knows that quicksort is quick; it says so right there in the name. It runs in O(n lg n) time with small constant factors. But for small arrays, or arrays which are mostly sorted already, you can do better by using insertion sort, which runs in O(n^2) time. Somewhere in the bowels of glibc is a highly-optimized quicksort which does exactly this: it drops down to insertion sort for subarrays of size 6 or less.
And don't even get me started on the effects of cache locality. The point is, sometimes intuition and analysis of algorithms can only go so far; at some point you've got to either test it or just call it "good enough" and think about something else.
- ckuehne 16y agoAt the risk of being pedantic: quicksort has a worst-case runtime of O(n^2).
- dgordon 16y agoAt the risk of being even more pedantic, quicksort with the O(n) deterministic median finding algorithm has a worst-case runtime of O(n log n) -- you use that algorithm to find the median each time and use that as the pivot. The constants would make it less efficient for most cases, though.