Introsort algorithm in .NET 4.5 – internal implementation details
Even though introspective sort was invented in 1997 (by David Musser) and was taken on by many frameworks no too long after, Microsoft decided to add it to the .NET platform only in 2012. However, it worth having a look at the implementation, it’s quite smartly written. Introsort Currently the fastest sorting algorithm is quicksort but it’s got a couple of edge cases when it performs really poorly – in O(n^2) time instead of the O(n*log(n)) typical runtime. Even though a smart pivot selection makes it practically impossible to have an O(n^2) runtime, “evil” input can force the sorting to fall into this, making the running time much longer than expected. Musser had two ideas to speed up the typical quicksort algorithm: If the algorithm on any sub-array runs longer than expected (recursion is deeper than log(array size) ) then let’s switch to heapsort which is guaranteed to finish in O(n*log(n)) time If the number of elements is small enough don’t use quicksort, si...