from wiki page of insertion sort:
Some divide-and-conquer algorithms such as quicksort and mergesort sort by recursively dividing the list into smaller sublists which are
then sorted. A useful optimization in practice for these algorithms is
to use insertion sort for sorting small sublists, where insertion sort
outperforms these more complex algorithms. The size of list for which
insertion sort has the advantage varies by environment and
implementation, but is typically between eight and twenty elements.
the quote from wiki has one reason is that, the small lists from merge sort are not worse case for insertion sort.
I want to just ignore this reason.
I knew that if the array size is small, Insertion sort O(n^2) has chance to beat Merge Sort O(n log n).
I think(not sure) this is related to the constants in T(n)
Insertion sort: T(n) = c1n^2 +c2n+c3
Merge Sort: T(n) = n log n + cn
now my question is, on the same machine, same case (worse case), how to find out the largest element number, let insertion sort beat merge sort?
It’s simple:
Take a set of sample arrays to sort, and iterate over a value k where k is the cutoff point for when you switch from merge to insertion.
then go
For what it’s worth, the
java.util.Arraysclass has this to say on the matter in its internal documentation:In its primitive sequences, it also uses 7, although it doesn’t use the constant value.