Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Which sorting algorithms does Arrays.sort use for primitive arrays and for object arrays, and why are they different?

For primitive arrays, Arrays.sort uses a tuned dual-pivot quicksort, with insertion sort for small ranges and other refinements, which is fast, works in place and is not stable. For object arrays it uses TimSort, a stable merge sort variant that is very fast on partially ordered data but needs extra memory. The difference exists because stability, keeping equal elements in their original order, is meaningless for primitives but matters for objects sorted by one key, and TimSort's checks are also why an inconsistent Comparator can fail with Comparison method violates its general contract.

Why this question is asked

Sorting is something we rarely implement ourselves, but knowing what the library does explains real behaviour: why sorting a list of orders by date keeps the earlier order of same-day orders, why a sort suddenly throws an exception after a comparator change, and why parallelSort is not always faster. Interviewers ask this to see whether we know the algorithms behind the API and the reasons for the choice. In this answer, we will recap what stability means, look at the dual-pivot quicksort used for primitives and TimSort used for objects, see the comparator exception TimSort can raise, and finish with parallelSort.

1A Quick Recap: What Stability Means

A sort is stable if elements that compare as equal keep the order they had before sorting. Stability matters when we sort by one key and care about an order that came from somewhere else. If a list of orders is already sorted by time and we then sort it by customer, a stable sort keeps each customer's orders in time order; an unstable one may shuffle them.

For primitives, stability cannot be observed. Two ints that are equal are identical: there is no way to tell which 5 was first. So a primitive sort is free to use the fastest algorithm, stable or not. For objects, two elements can be equal by the comparator yet be different objects with different other fields, so stability is visible and valuable.

2Primitive Arrays: Dual-Pivot Quicksort

Classic quicksort picks one pivot, partitions the array into elements smaller and larger than it, and recurses. Dual-pivot quicksort, introduced in JDK 7, picks two pivots and partitions into three parts, which in practice does fewer comparisons and makes better use of the CPU cache. It sorts in place, using no extra array, and it is not stable.

Java
int[] nums = {5, 3, 9, 1, 5, 7};
Arrays.sort(nums); // [1, 3, 5, 5, 7, 9]
Arrays.sort(nums, 1, 4); // sorts only indexes 1 to 3
double[] d = {0.0, -0.0, Double.NaN, -1.0};
Arrays.sort(d); // [-1.0, -0.0, 0.0, NaN]: total order, NaN last

The JDK version is heavily tuned. Small ranges are finished with insertion sort, which is faster than quicksort for a few dozen elements. Since JDK 14, the implementation also detects runs that are already sorted and merges them, and it switches to heap sort if partitioning goes badly, which keeps the worst case at O(n log n) instead of quicksort's O(n^2) (details vary by version). Notice the double example: floating-point values are sorted with the total order of Double.compare, so -0.0 comes before 0.0 and NaN goes last.

3Object Arrays: TimSort

For Object[] and arrays sorted with a Comparator, the JDK uses TimSort, also since JDK 7, originally designed by Tim Peters for Python. It scans the array for runs, stretches that are already ascending or strictly descending, reversing the descending ones, and extends short runs to a minimum length with binary insertion sort. Then it merges runs pairwise, following rules that keep the merges balanced, and uses galloping, a binary search that skips ahead when one run keeps winning, to merge quickly.

Java
record Order(String customer, int time) {}
Order[] orders = { new Order("bo", 1), new Order("ana", 2), new Order("bo", 3), new Order("ana", 4) };
Arrays.sort(orders, Comparator.comparing(Order::customer));
// [ana 2, ana 4, bo 1, bo 3] each customer's orders keep their time order: stable
The two algorithms side by side
Primitives: dual-pivot quicksortObjects: TimSort
StableNo (not observable anyway)Yes, guaranteed
Extra memoryIn placeUp to n/2 references
Best caseFast on runs (JDK 14+)About O(n) on sorted or nearly sorted data
Worst caseO(n log n) with heap sort fallbackO(n log n)
Bad comparatorNot applicableMay throw IllegalArgumentException

Because real data often contains existing order, such as a list that is sorted except for a few new items at the end, TimSort is often close to O(n) in practice, while its worst case is O(n log n). The price is memory: merging needs a temporary array of up to half the input size. For objects that is acceptable, since the array holds references, and the stability it buys is part of the documented contract of Arrays.sort for objects, so code may rely on it.

4When TimSort Throws: Comparison Method Violates Its General Contract

A Comparator must be consistent: if a < b then b > a, if a < b and b < c then a < c, and the answer must not change during the sort. TimSort relies on these rules when it merges, and when it notices that they were broken, it stops with IllegalArgumentException: Comparison method violates its general contract! The exception appears only for some inputs and sizes, because small arrays are sorted with binary insertion sort, which does not detect the problem, which makes it look random.

Java
// Bug 1: subtraction overflows
Integer[] o = {Integer.MIN_VALUE, 1, 0};
Arrays.sort(o, (p, q) -> p - q); // [0, 1, -2147483648]: wrong order
Arrays.sort(o, Integer::compare); // [-2147483648, 0, 1]
// Bug 2: a comparator whose answer is not stable
Arrays.sort(bigArray, (p, q) -> random.nextInt(3) - 1);
// IllegalArgumentException: Comparison method violates its general contract!

The common real causes are subtraction that overflows, comparing on a field that another thread changes during the sort, and comparators that treat null or NaN inconsistently. The fix is to build comparators with Comparator.comparing, comparingInt, thenComparing and nullsFirst, which are correct by construction. There is also a system property, java.util.Arrays.useLegacyMergeSort=true, that switches back to the old merge sort, which hides the exception, but it leaves the comparator broken and the results unreliable.

5Arrays.parallelSort

Arrays.parallelSort, added in Java 8, splits a large array into chunks, sorts them in parallel on the common ForkJoinPool and merges the results. For arrays below a threshold, 8,192 elements in current JDKs, it simply sorts sequentially, because coordinating threads would cost more than it saves. For very large arrays on a multi-core machine it can be several times faster. But it competes for the common pool with parallel streams and other work in the same JVM, so in a busy server handling many requests, plain Arrays.sort is often the better choice. For objects it keeps the stability guarantee.

6Follow-up questions

Which algorithm do Collections.sort and List.sort use?

The same TimSort. List.sort's default implementation copies the list into an array, sorts it with Arrays.sort and writes the elements back, and Collections.sort simply calls list.sort. ArrayList overrides sort to sort its internal array directly, without the copy. So everything said about stability, memory and the comparator contract applies to sorting lists too.

Why not use TimSort for primitives as well, for consistency?

Because it would cost memory and speed for no benefit. Stability, TimSort's main advantage, is invisible for primitive values, and TimSort needs a temporary buffer of up to half the array, which for a large long[] means many megabytes. Quicksort in place, with its excellent cache behaviour on contiguous primitive data, is simply the faster choice. The JDK picks the best algorithm for each kind of data instead of one algorithm for all.

Is Arrays.sort guaranteed to be O(n log n)?

For objects, yes: TimSort's worst case is O(n log n). For primitives, the classic quicksort worst case is O(n^2) on adversarial input, and older JDKs were exposed to that in theory; the current implementation falls back to heap sort when partitioning degrades, which keeps it at O(n log n). The documentation describes the algorithms only as implementation notes, so we rely on the stability guarantee for objects, which is specified, and treat the rest as current behaviour.

7Conclusion

In this answer, we saw that Arrays.sort uses a tuned dual-pivot quicksort for primitive arrays, in place and not stable, because equal primitives cannot be told apart, and TimSort for object arrays, a stable merge sort that exploits existing runs and needs up to n/2 extra references, because stability matters when sorting objects by one key. TimSort can throw Comparison method violates its general contract when a comparator is inconsistent, which we avoid with Comparator.comparing and Integer.compare instead of subtraction, and parallelSort splits large arrays on the fork/join pool but sorts small ones sequentially.

What to say in the interviewAbout 100 seconds aloud

Open with

For primitive arrays, Arrays.sort uses a dual-pivot quicksort, which has been there since JDK 7 and has been tuned since: it uses insertion sort for small ranges, it detects already sorted runs in newer versions, and it falls back to heap sort so the worst case stays at n log n.

Then, if they want more

It works in place and isn't stable, but stability doesn't matter for primitives, because two equal ints are indistinguishable. For object arrays, and anything sorted with a Comparator, it uses TimSort, a stable merge sort variant: it finds existing ascending or descending runs, extends short ones with binary insertion sort, and merges them with galloping.

That makes it close to linear on partially ordered data, which is common in practice, and it needs a temporary buffer of up to half the array.

Stability matters for objects because they can compare equal on the sort key but differ in other fields, for example sorting orders by customer keeps each customer's orders in time order, and that guarantee is part of the documented contract.

One practical consequence of TimSort is the exception Comparison method violates its general contract, which it throws when it detects an inconsistent comparator, typically subtraction that overflows or a field that changes during the sort; the fix is Comparator.comparing or Integer.compare, not the legacy merge sort flag.

Finally, parallelSort splits large arrays across the common ForkJoinPool, but below about 8,192 elements it just sorts sequentially, and on a busy server the sequential sort is often the better choice.

About this answer

Last updated
12 November 2026
Versions it names
Java 7, Java 14, Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Which sorting algorithms does Arrays.sort use for primitive arrays and for object...": https://scrivio-interview-library.netlify.app/java/arrays/78a27ef580/