3 ms·
The best algorithm may change depending on your constraints and the input. You could argue that quicksort is best based on its O(n lg n) average running time. I
by fredophile 13y ago
The best algorithm may change depending on your constraints and the input. You could argue that quicksort is best based on its O(n lg n) average running time. It is usually taught early on in CS programs as an example of a fast sorting algorithm. However, for small values of n you're actually better off using a sorting algorithm with worse asymptotic performance that is better suited to your hardware. Good cache coherency can make a big difference and asymptotic running times can hide some pretty big constants. Quicksort also performs badly on sorted or nearly sorted lists. In these cases you end up hitting quicksort's worst case performance of O(n^2).
You might have other constraints on your sorting algorithm. What if you wanted to sort twice and have ties in the second sort broken by the results of the first sort? You'd need to pick a stable sorting algorithm for your second sort. Someone else already mentioned in place sorting. If you have lots of items to sort but they are all relatively short you might find that a radix sort is fastest. You might not even really need to sort your items. If you just need to always be able to get the smallest or largest you could store your values in a heap.
To sum up, the best sorting algorithm will depend on your hardware, your data, and how you're planning to use it.