LOGBOOK

HELP

Quiz Entry - updated: 2026.12.02

How can merge-sort skip a merge with a single comparison, and what does that do for input that is already sorted?

Before merging, compare the last element of the left half with the first element of the right half. If the left one is not larger, the halves are already in order and are simply appended one after the other. On sorted input every merge shrinks to that one comparison: $n - 1$ comparisons in total instead of about $n \log_2 n$.

Both halves are sorted, so the largest element of the left half is its last one and the smallest element of the right half is its first one. If last(A) ≤ first(B), every element of $A$ is at most every element of $B$, and a full merge would only copy $A$ and then $B$. One comparison proves that, so the merge can be replaced by appending.

Java 6 documented this optimisation for Collections.sort: a "modified mergesort" in which the merge is omitted when the highest element of the low sublist is less than the lowest element of the high sublist. The guarantee stays $O(n \log n)$; what improves is the best case. On already sorted input each of the $n - 1$ merges costs one comparison, so the comparisons drop to linear, although the copying still happens on every level. TimSort, which replaced that sort in Java 7, takes the idea further: it looks for runs that are already sorted and merges only those.

The test with $\le$ instead of $<$ is safe for stability: if the halves only touch at equal keys, appending $A$ before $B$ keeps them in input order.

Go deeper:

From Quiz: ADS / Merge-Sort and Quick-Sort | Updated: Dec 02, 2026