Sorting and searching
What Java's sorts actually are, why TimSort exists, and binary search on the thing you forgot to sort.
You will almost never write a sort. You will choose one, rely on its guarantees, and occasionally be surprised by which guarantee you did not have — so this lesson is about what Java actually runs and what it promises.
Two different sorts, chosen by the type
Arrays.sort(int[] xs) // dual-pivot quicksort
Arrays.sort(Object[] xs) // TimSort
Collections.sort(list) // TimSort, via Arrays.sortThat split is deliberate and worth knowing the reason for.
Primitives get dual-pivot quicksort. In place, no extra array, excellent cache behaviour — and not stable, which does not matter, because two ints with the same value are indistinguishable. There is nothing to preserve.
Objects get TimSort. It allocates temporary space and it is stable, which for objects matters enormously — and the next section is why.
Stability is a guarantee you will want before you know you want it
A stable sort keeps equal elements in the order they were already in.
Five employees, sorted by department only:
### ana/eng cy/eng ed/eng bo/ops di/opsana, cy and ed kept the order they had in the input. That is stability, and it is what makes sorting by two things work without a compound comparator:
list.sort(comparing(Emp::name)); // sort by name first
list.sort(comparing(Emp::dept)); // then by dept — names stay ordered within each deptWith an unstable sort that second line would scramble the first. You would have to write comparing(Emp::dept).thenComparing(Emp::name) — which is clearer anyway and the better habit, but the point is that Java's object sort gives you the choice, and its primitive sort does not.
TimSort earns its keep in a second way: it detects runs that are already ordered and merges them, so nearly-sorted data is close to O(n) rather than O(n log n). Real data is very often nearly sorted — appended in time order, re-sorted after a small edit — and that is why TimSort is the default in Java, Python and elsewhere.
Binary search, and the precondition nobody enforces
### array : [5, 2, 9, 1, 7]
### search 9 : 2 <- correct, by luck
### search 1 : -1 <- not found, but 1 is at index 3Arrays.binarySearch on an unsorted array does not throw, does not warn, and is sometimes right. Searching for 9 returned the correct index. Searching for 1 said "not present" about an element sitting at index 3.
That is the worst failure mode available: an operation that works often enough to pass a test and fails on data you did not try. The precondition is in the Javadoc and nowhere in the type system, which means it is your job:
The array must be sorted prior to making this call. If it is not sorted, the results are undefined.
And "undefined" here does not mean an exception. It means whatever the halving happens to land on.
Binary search is O(log n) and the arithmetic is worth internalising: a billion elements is thirty steps. Which is the same shape as a database index — the indexes lesson's B-tree is binary search generalised to disk, and it is why a where id = ? on a huge table is instant.
Which searching, actually
| You have | Use |
|---|---|
a HashMap/HashSet | get / contains — O(1), and no sorting needed |
a sorted array or List | binarySearch — O(log n) |
a TreeMap | get, or floorKey/ceilingKey/subMap for ranges |
| an unsorted list, searched once | just scan it — sorting to search once is slower |
| an unsorted list, searched often | build a HashSet — the big-O lesson measured this |
That last row is the decision that matters in ordinary code, and it is nearly always the right one. Sorting costs O(n log n) once; a hash set costs O(n) to build and O(1) per query. If you are searching more than a handful of times, the set wins outright and needs no precondition anybody can break.
The comparator contract, which sorting enforces at run time
A comparator must be consistent: if a < b and b < c then a < c, and compare(a,b) must be the negation of compare(b,a).
Break it and TimSort will, sometimes, throw:
java.lang.IllegalArgumentException: Comparison method violates its general contract!It is thrown from the merge, so it appears on some inputs and not others, and typically in production on a larger data set than your tests had. The classic cause is a comparator that subtracts — a.value - b.value — which overflows for large or negative values and produces the wrong sign. Use Integer.compare(a, b).
The comparable-and-comparator lesson in the collections course takes the contract apart properly, including consistency with equals.
Under the hood: how TimSort actually finds the near-O(n) case, and why dual-pivot quicksort cannot be stable
TimSort's trick is not merge sort with a marketing name — it starts by scanning the array for runs: maximal stretches that are already ascending, or strictly descending (which it reverses in place to make ascending). A fully-sorted array is discovered to be one giant run in a single linear pass, and TimSort then does essentially nothing else — which is the mechanism behind "nearly-sorted data is close to O(n)" rather than a vague performance claim. Runs shorter than a minimum length (minrun, computed from the array size, typically between 32 and 64) are extended with a simple insertion sort, because insertion sort is genuinely fast on small or nearly-sorted input despite being O(n²) in general — a small, well-chosen constant-factor optimisation folded into an otherwise O(n log n) algorithm. Once runs exist, TimSort merges them pairwise, and it is precisely because merging two adjacent runs never has to reorder equal elements relative to each other that stability falls out of the algorithm for free — a merge only ever asks "which run's front element is smaller", and ties keep the left run's element first by construction.
Dual-pivot quicksort cannot offer that guarantee, and it is not an oversight — it is what makes it fast. Quicksort partitions in place by swapping elements across the array based on comparisons to pivots; a swap that moves an element past another equal element has no memory of which one arrived first, so any information about original order is destroyed by the same in-place swapping that avoids allocating a second array. That is the real trade the lesson's opening code split states: dual-pivot quicksort's in-place, no-extra-array, cache-friendly swapping is incompatible with stability, not merely untested for it — you cannot have both an in-place comparison sort and a stability guarantee in general, which is precisely why primitives (where equal elements are truly indistinguishable, so nothing is lost) get the unstable-but-faster algorithm and objects (where two "equal" records can still differ in ways compareTo does not see, like the five employees sorted by department alone) get the allocating, stable one.
Try it yourself
Predict what a stable sort preserves
record Emp(String name, String dept) {}
List<Emp> emps = new ArrayList<>(List.of(
new Emp("cy", "eng"), new Emp("ana", "eng"), new Emp("bo", "ops"),
new Emp("ed", "eng"), new Emp("di", "ops")
));
emps.sort(Comparator.comparing(Emp::dept));
System.out.println(emps.stream().map(e -> e.name() + "/" + e.dept()).toList());Before running it: the list starts as cy, ana, bo, ed, di and is sorted by department only. Which order do the three eng employees end up in relative to each other?
Why the eng employees keep their original relative order
List.sort on objects is TimSort, and TimSort is stable: elements that compare equal — here, every eng employee compares equal to every other eng employee, since the comparator only looks at dept — keep the relative order they had in the input. cy appeared before ana, which appeared before ed, so that is the order they hold within the eng group after sorting, even though nothing in the comparator ever compared their names. This is the exact mechanism that makes "sort by name, then sort by department" work as two separate calls instead of needing a single combined comparator.
Misconceptions
- "TimSort is just merge sort." It is a merge sort with an insertion-sort-based run-detection front end bolted on specifically to exploit already-ordered data, which is where its near-O(n) best case comes from — plain merge sort has no such fast path and is Θ(n log n) even on a fully sorted array.
- "An unstable sort is just as good as long as I do not care about ties." Ties are exactly the case where "I do not care" is often wrong without realising it — a UI re-sorting a result list by a second column, a report grouped by one field and expected to keep a prior order within each group, both silently depend on stability the first time two rows tie.
Sources
- Tim Peters, the original TimSort description (written for CPython's
list.sort, adopted by the JDK forArrays.sort(Object[])andCollections.sort). - OpenJDK
java.util.TimSortandjava.util.DualPivotQuicksortsource and class-level documentation. - Robert Sedgewick and Kevin Wayne, Algorithms (4th ed.) — sorting stability, and why an in-place partitioning sort cannot generally guarantee it.