What does Java's TimSort do with fewer than 32 elements, and why?
It does not merge at all: a range shorter than 32 elements (the constant MIN_MERGE) is sorted with binary insertion sort. For tiny inputs insertion-sort's small constant factor beats the merging machinery, and the threshold of 32 was found by measuring.
Binary insertion sort is insertion-sort with one change: the slot for the next element is found by binary search in the sorted part, so each element needs only $O(\log n)$ comparisons; shifting the larger elements one place to the right still costs up to $O(n)$ moves. Large arrays get the same treatment at the bottom: TimSort scans the input for runs that are already sorted, extends every run shorter than a minimum length (between 16 and 32 elements) with binary insertion sort, and only then starts merging.
The source shows how far the tuning goes:
MIN_MERGE = 32: Tim Peters' original C version for Python used 64; in Java, 32 measured faster.- To make room in the sorted part, a block of larger elements is moved with
System.arraycopy, a native method that copies much faster than a Java loop. A block of only one or two elements, though, is shifted by hand in aswitch, because for so few elements the call costs more than the copy. - The element being inserted is called
pivotin the source, which has nothing to do with quick-sort's pivot.
So a simple $O(n^2)$ algorithm does the bottom layer of the standard library's $O(n \log n)$ sort: the asymptotic class decides for large $n$, constant factors decide for small $n$.
Go deeper:
TimSort.java (OpenJDK source) —
MIN_MERGE,binarySortwith its hand-written shift, and the run-merging logic.listsort.txt (CPython) — Tim Peters' own description of the algorithm, with the reasoning behind every threshold.