How Java sorts
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Java uses Dual-Pivot Quicksort for primitive arrays and stable TimSort for objects and collections.
Primitive Sorting: Dual-Pivot Quicksort
Arrays.sort on a primitive array uses Dual-Pivot Quicksort, which is fast but makes no promise about equal values. The program below sorts five marks.
import java.util.Arrays;
public class PrimitiveSort { public static void main(String[] args) { int[] marks = {72, 95, 38, 95, 61}; Arrays.sort(marks); // int[]: Dual-Pivot Quicksort System.out.println(Arrays.toString(marks)); }}[38, 61, 72, 95, 95]
Dual-Pivot Quicksort is the algorithm Arrays.sort uses for primitive arrays like int[] or double[].
Primitives carry no object identity, so stability has zero practical meaning.
Instead, execution speed and CPU cache locality are the absolute top priorities.
Dual-Pivot Quicksort was designed by Vladimir Yaroslavskiy and integrated into Java 7.
Classical quicksort uses one pivot to partition an array into two regions.
Dual-Pivot Quicksort picks two pivots, P1 and P2, satisfying P1 <= P2.
It partitions the array into three parts: less than P1, between P1 and P2, and greater than P2.
This three-way split reduces the depth of recursion and minimizes cache misses.
For small arrays with fewer than 47 elements, Java falls back to insertion sort.
Insertion sort has minimal constant overhead and avoids recursive method calls.
For arrays without duplicate keys, Dual-Pivot Quicksort runs faster than traditional quicksort.
It achieves average O(n log n) time while maintaining pure in-place execution.
Object Sorting: TimSort and Stability
Arrays.sort on objects uses TimSort, which is stable: equal values keep their original order. The example sorts the same numbers as primitives and as objects.
Example 1 · Primitive Sorting Versus Object Sorting
import java.util.Arrays;import java.util.Comparator;
public class SortTypesDemo { public static void main(String[] args) { // 1. Primitive sorting (Dual-Pivot Quicksort) int[] primitives = {5, 2, 8, 1, 9}; Arrays.sort(primitives); System.out.println("Primitives: " + Arrays.toString(primitives));
// 2. Object sorting (TimSort, reverse order) Integer[] objects = {5, 2, 8, 1, 9}; Arrays.sort(objects, Comparator.reverseOrder()); System.out.println("Objects reverse: " + Arrays.toString(objects)); }}Primitives: [1, 2, 5, 8, 9] Objects reverse: [9, 8, 5, 2, 1]
What this code does
- Arrays.sort(int[]) uses Dual-Pivot Quicksort in place.
- Arrays.sort(Integer[], Comparator) invokes stable TimSort.
- Comparator.reverseOrder() inverts natural ordering for objects.
When sorting object arrays or collections, Java uses TimSort. Objects often contain multiple attributes, such as users with names and ages. Sorting must be stable so earlier sort orders are preserved for equal keys. TimSort was originally created by Tim Peters for Python and adopted by Java. TimSort is an adaptive hybrid combining merge sort and insertion sort. Real-world datasets frequently contain chunks that are already sorted, called runs. TimSort identifies natural sorted runs and extends short runs using binary insertion sort. It then pushes runs onto a stack and merges them using balanced merge policies. TimSort guarantees worst-case O(n log n) time and stable execution. On already sorted data, it detects a single run and terminates in linear O(n) time. Its auxiliary space complexity is at most O(n/2) in the worst case. This makes TimSort the standard engine for Arrays.sort(Object[]) and List.sort().
Collections.sort, List.sort, and Comparator Contracts
List.sort and Collections.sort take a Comparator that says how two items compare. The examples sort employees by several fields and show a comparison that cannot overflow.
Example 2 · Multi-Field Sorting with Comparator Combinators
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class MultiFieldSortDemo { static class Employee { String dept; int salary; String name;
Employee(String dept, int salary, String name) { this.dept = dept; this.salary = salary; this.name = name; }
public String toString() { return dept + ":" + salary + ":" + name; } }
public static void main(String[] args) { List<Employee> staff = new ArrayList<>(); staff.add(new Employee("Eng", 90000, "Bob")); staff.add(new Employee("Sales", 80000, "Alice")); staff.add(new Employee("Eng", 90000, "Carol")); staff.add(new Employee("Eng", 85000, "Dave"));
staff.sort(Comparator.comparing((Employee e) -> e.dept) .thenComparing((Employee e) -> -e.salary) .thenComparing((Employee e) -> e.name));
for (Employee e : staff) { System.out.println(e); } }}Eng:90000:Bob Eng:90000:Carol Eng:85000:Dave Sales:80000:Alice
What this code does
- Primary sort groups employees by department alphabetically.
- Secondary sort orders salaries in descending order within each department.
- Tertiary sort breaks ties alphabetically by employee name.
Example 3 · Safe Comparison Without Integer Overflow
import java.util.Arrays;
public class SafeComparatorDemo { public static void main(String[] args) { int a = Integer.MIN_VALUE; int b = 1;
// Unsafe subtraction: (a - b) overflows to positive int unsafeDiff = a - b; System.out.println("Unsafe subtraction sign: " + (unsafeDiff > 0 ? "positive" : "negative"));
// Safe comparison via Integer.compare int safeResult = Integer.compare(a, b); System.out.println("Safe compare sign: " + (safeResult < 0 ? "negative" : "positive"));
// Safe sorting of array containing extreme numbers Integer[] nums = {Integer.MIN_VALUE, 0, Integer.MAX_VALUE}; Arrays.sort(nums, (x, y) -> Integer.compare(x, y)); System.out.println("Safely sorted: " + Arrays.toString(nums)); }}Unsafe subtraction sign: positive Safe compare sign: negative Safely sorted: [-2147483648, 0, 2147483647]
What this code does
- Integer.MIN_VALUE minus 1 overflows to positive, yielding a wrong comparison.
- Integer.compare inspects values directly without arithmetic subtraction.
- Prevents IllegalArgumentException caused by broken comparator contracts.
In modern Java, Collections.sort(list) delegates directly to list.sort(null). Sorting a List uses TimSort behind the scenes by extracting an object array. You customize sorting rules by providing a Comparator instance. Java 8 introduced clean combinators like Comparator.comparing() and thenComparing(). A Comparator must strictly satisfy the mathematical contract of a strict weak ordering. First, antisymmetry requires compare(a, b) == -compare(b, a). Second, transitivity requires that if a < b and b < c, then a < c. Third, transitivity of equivalence requires that if a == b and b == c, then a == c. A common beginner mistake is writing (a - b) as a comparator. If a is a large positive integer and b is negative, integer subtraction overflows. The overflow flips the sign, violating transitivity and throwing an exception. Always use Integer.compare(a, b) or Comparator.naturalOrder() to compare safely.
Fix the error
Fix the comparator
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Sort the names by length.
Error
SortFix1.java:6: error: cannot find symbol
names.sort((a, b) -> a.length - b.length);
^
symbol: variable lengthNext step
Check your understanding
10 quick questions