man java/sorting

Why Java sorts ints and objects differently

lib / Java 8 mindraft

checked against: OpenJDK 27.0.1.1

Why does Arrays.sort use one algorithm for an int[] and a different one for an Integer[] holding the same numbers, and why is the second one three times slower?

int[] prim = base.clone();
Integer[] boxed = Arrays.stream(base).boxed().toArray(Integer[]::new);
Arrays.sort(prim);    // DualPivotQuicksort
Arrays.sort(boxed);   // ComparableTimSort

This article reads java/util/Arrays.java, DualPivotQuicksort.java, TimSort.java, Collections.java, List.java and ArrayList.java from openjdk/jdk27u at the tag jdk-27.0.1.1-ga, the tag the Homebrew formula builds, and checks them with small programs on that build (OpenJDK 27.0.1.1) on an Apple M2 Pro.

The short version

The answer is stability. A stable sort keeps equal elements in their original order. For objects that is visible: two records with the same sort key can be told apart afterwards. For an int, two equal values are the same value, so nobody can tell whether they swapped. The Arrays class documentation makes stability a requirement for objects and leaves the algorithm open (L58-L64): the algorithm behind sort(Object[]) “does not have to be a MergeSort, but it does have to be stable”. So objects get TimSort, a stable merge sort, and primitives get a dual-pivot quicksort, which moves equal values around freely and partitions in place.

Who calls what

Arrays.sort(int[])               -> DualPivotQuicksort.sort(a, 0, 0, a.length)
Arrays.parallelSort(int[])       -> DualPivotQuicksort.sort(a, parallelism, ...)
Arrays.sort(Object[])            -> ComparableTimSort.sort(...)
Arrays.sort(T[], Comparator)     -> TimSort.sort(...)
Collections.sort(list, c)        -> list.sort(c)
ArrayList.sort(c)                -> Arrays.sort(elementData, 0, size, c)
List.sort(c) (default method)    -> toArray(), Arrays.sort, write back

Arrays.sort(int[]) is one line (L98-L100). Arrays.sort(Object[]) (L1034-L1039) and the comparator version (L1223-L1232) go to ComparableTimSort and TimSort. ComparableTimSort calls itself “a near duplicate of TimSort, modified for use with arrays of objects that implement Comparable” (ComparableTimSort.java L29-L41). Both first check LegacyMergeSort.userRequested, a system property kept “to be removed in a future release”. Collections.sort is now just list.sort(c) (Collections.java L179-L181). The default List.sort copies the list to an array, sorts it and writes the elements back through a ListIterator (List.java L510-L518), and ArrayList overrides it to sort its own backing array in place (ArrayList.java L1817-L1827).

Stability is easy to see with records:

record Word(String text, int count) {}
// pear 2, fig 3, kiwi 2, lime 3, plum 1, date 2
words.sort(Comparator.comparingInt(Word::count).reversed());
$ java Stable.java
[Word[text=fig, count=3], Word[text=lime, count=3], Word[text=pear, count=2], Word[text=kiwi, count=2], Word[text=date, count=2], Word[text=plum, count=1]]

Within each count the words keep their input order, and reversed() flips the comparison without flipping ties.

Dual-pivot quicksort

A classic quicksort picks one pivot and splits the array in two. Vladimir Yaroslavskiy’s dual-pivot version picks two, p1 < p2, and splits it in three: below p1, between, and above p2. The current code is much more than that. The main loop (DualPivotQuicksort.java L253-L386) tries, in order:

  1. Mixed insertion sort for a part that isn’t the leftmost and is shorter than 65 plus a depth term. The pivot to its left is smaller than everything in it and acts as a sentinel, so the inner loop needs no bounds check (L555-L572).
  2. Plain insertion sort for any part shorter than 44.
  3. Merging runs for the whole array, and for inner parts over 4,096 elements. It scans for ascending, descending and constant stretches. It gives up if the first run is shorter than 16, if the first runs are short on average, or once it has counted 5,120 runs. Otherwise it merges them through a buffer as large as the range (tryMergeRuns, L753-L863).
  4. Heap sort when the recursion has gone 64 levels deep (MAX_RECURSION_DEPTH = 64 * DELTA, with bits += DELTA per level), so no input can make it quadratic (L707).
  5. Otherwise partition. Five sample elements, spaced by “an inexpensive approximation of the golden ratio” (L291), are sorted with a small sorting network. If all five differ, the first and fifth become the two pivots. If any two are equal, it switches to a single pivot and a three-way split, so arrays full of duplicates don’t degrade.

The run detection shows what giving up stability buys. A descending stretch is found with a[k - 1] >= a[k] (L780) and reversed in place, equal values included. TimSort may only reverse strictly descending runs, because reversing equal elements would swap them (TimSort.java L330-L364).

Both sort and partition are marked @IntrinsicCandidate. On x86_64 with AVX2 or AVX-512, HotSpot loads a libsimdsort library and replaces them with vectorised code (stubGenerator_x86_64.cpp L4997-L5016). The AArch64 stub generator at the same tag has no array-sort stub, so on an Apple M2 the Java code above is what runs.

TimSort

TimSort is Tim Peters’s list sort for Python, adapted by Josh Bloch (TimSort.java L28-L61). It walks the array once, finding natural runs, ascending or strictly descending. A descending run is reversed. A run shorter than minRun is extended with a binary insertion sort, and the runs are pushed on a stack and merged when their lengths break two invariants (L422-L450). Arrays shorter than MIN_MERGE = 32 skip the merging entirely. minRun comes out between 16 and 32 (L400-L408). The comment on MIN_MERGE says Python used 64 and that 32 “was empirically determined to work better in this implementation” (L62-L80). A merge switches into galloping mode, an exponential search for where the next element goes, when one side wins minGallop times in a row. That starts at MIN_GALLOP = 7 and moves up for random data and down for structured data (L90-L103). Merging needs a temporary array of up to n/2 references.

Its strength is input that is already partly in order. I counted comparator calls on 100,000 Integers:

static long count(Integer[] a) {
    calls = 0;
    Arrays.sort(a, (x, y) -> { calls++; return x.compareTo(y); });
    return calls;
}
$ java Counts.java
random:          1534685
already sorted:  99999
reversed:        100040
sorted + 100:    102470

Random input costs about n log2 n comparisons (n log2 n is 1.66 million here). Sorted input costs n - 1. A sorted array with 100 random values appended costs 2.5% more than sorted.

When the comparator lies

TimSort checks the comparator’s consistency as a side effect. If a merge finds a state that a valid ordering can’t produce, it throws (L782):

Random r = new Random(1);
Arrays.sort(a, (x, y) -> r.nextInt(3) - 1);   // not a valid order
$ java Broken.java
java.lang.IllegalArgumentException: Comparison method violates its general contract!
x - y:           [0, 2147483647, -3, 5, -2147483648]
Integer::compare: [-2147483648, -3, 0, 5, 2147483647]

The second and third lines are a more common lie. (x, y) -> x - y looks like a comparator, but the subtraction overflows for values far apart, and {MIN_VALUE, 5, -3, MAX_VALUE, 0} comes out in nonsense order with no exception. Integer::compare gets it right.

Doubles have two extra problems

< doesn’t order all doubles. -0.0 == 0.0 is true, and NaN is neither smaller nor larger than anything. So Arrays.sort(double[]) uses the order of Double.compareTo: -0.0 before 0.0, and every NaN after every other value (L332-L352). Here equal-looking values can be told apart, and the documented order puts -0.0 first every time.

What boxing costs

Sorting a million random ints, five times in one process, each on a fresh copy:

long t0 = System.nanoTime();
Arrays.sort(prim);
long t1 = System.nanoTime();
Arrays.sort(boxed);
long t2 = System.nanoTime();
$ java SortTimes.java
round 1: int[] 68.0 ms, Integer[] 238.4 ms
round 2: int[] 53.3 ms, Integer[] 191.1 ms
round 3: int[] 52.4 ms, Integer[] 161.8 ms
round 4: int[] 52.6 ms, Integer[] 157.2 ms
round 5: int[] 52.8 ms, Integer[] 156.7 ms

From the third round on, the Integer[] sort takes three times as long. An int[] is one block of 4-byte values. An Integer[] is an array of references to separate objects, every comparison is a compareTo call on two of them, and the merges need a temporary array. Both are slowest in the first round, while the JVM is still warming up.

Curious facts

  • DualPivotQuicksort’s @since tag reads 1.7 * 14. The class came in Java 7 and was reworked in JDK 14.
  • Before that rewrite, the documentation said the algorithm offers O(n log n) “on many data sets that cause other quicksorts to degrade to quadratic performance”. In JDK 14 and later it says “on all data sets”, because the heap-sort fallback guarantees it (JDK 13 version).
  • The primitive sort reverses non-strictly descending runs; TimSort may only reverse strictly descending ones.
  • Arrays.parallelSort(int[]) runs the same DualPivotQuicksort with the common pool’s parallelism (L524-L526).
  • TimSort starts with a small temporary array, half the array length below 512 elements and 256 slots otherwise, and grows it when a merge needs more (L146-L160).

History

  • Java 7: dual-pivot quicksort for primitive arrays (JDK-6880672), and TimSort for objects (JDK-6804124). Oracle’s Java SE 7 compatibility notes warn that the new sort “may throw an IllegalArgumentException” for an invalid Comparable and name java.util.Arrays.useLegacyMergeSort as the way back.
  • Java 8: List.sort becomes a default method, and Arrays.parallelSort arrives (both @since 1.8).
  • JDK 11: JDK-8203864 adds a second check to TimSort’s mergeCollapse, following the analysis in “On the Worst-Case Complexity of TimSort” by Auger, Jug, Nicaud and Pivoteau.
  • JDK 14: JDK-8226297, “Dual-pivot quicksort improvements”, brings mixed insertion sort, the heap-sort fallback and the current run merging.
  • JDK 22: AVX-512 intrinsics for sorting int, long, float and double arrays on x86_64 (JDK-8309130).
  • JDK 23: AVX2 intrinsics for int and float arrays (JDK-8319577).

Sources

ls java/

  • draft How Java's HashMap works: buckets, treeification and hash spreadingWhat OpenJDK 27's HashMap does with a key: a power-of-two array of buckets, one XOR to spread the hash, chains that turn into red-black trees past eight nodes, doubling that keeps chain order, and why a map of Integer keys iterates in the same order on every run.