Sorting Algorithms in Java
Java's standard library has one of the most carefully engineered sorting setups of any language — it uses different algorithms depending on whether you sort objects or primitives. This guide covers both the built-ins and clean implementations of the core algorithms.
The built-in sorts
Arrays.sort(Object[]) and Collections.sort() use Tim Sort (stable). Arrays.sort(int[]) and other primitive overloads use Dual-Pivot Quick Sort, which is faster for primitives where stability is irrelevant. Use a Comparator for custom orderings.
Why two algorithms?
Objects need stability for correct multi-key sorting, so Java uses stable Tim Sort. Primitives have no identity beyond their value, so stability is meaningless — and Dual-Pivot Quick Sort partitions around two pivots for excellent cache performance. See what algorithm Java uses for the details.
Quick Sort in Java
void quickSort(int[] a, int lo, int hi) {
if (lo < hi) {
int p = partition(a, lo, hi);
quickSort(a, lo, p - 1);
quickSort(a, p + 1, hi);
}
}Frequently asked questions
What sorting algorithm does Java use? +
Why does Java use different sorts for primitives and objects? +
See it in motion
Watch this algorithm and 9 others run step by step in our free interactive visualizer.
▶ Launch Visualiser