Video in progress
Which algorithm runs inside List.sort() and Arrays.sort(), are they stable, and what does that mean in practice?
For objects it is TimSort, which is stable and very fast on partially sorted data. For primitive arrays it is Dual-Pivot Quicksort, which is not stable, but with primitives you can't tell. Because it is stable, you can rely on the order of equal elements.
📖 Answer
Arrays.sort(Object[]), Collections.sort and List.sort use TimSort (a hybrid of merge sort and insertion sort). ArrayList.sort sorts the internal array in place. The default List.sort copies the list into an array, sorts it and writes it back with a ListIterator, so sorting a LinkedList is O(n log n) too.
What you should know about TimSort:
- it is stable: elements that are equal by the comparator keep their original order;
- it finds ready-made "runs", meaning chunks that are already ordered, so an almost sorted list is sorted in close to O(n);
- the worst case is O(n log n), with extra memory up to n/2.
Arrays.sort(int[]) is Dual-Pivot Quicksort. It is not stable, but you can't tell two equal ints apart, so it doesn't matter. For large arrays there is Arrays.parallelSort, which splits the work across the ForkJoin pool.
Where stability matters in practice:
// the user clicked the date column first, then the status column in a table
orders.sort(Comparator.comparing(Order::createdAt));
orders.sort(Comparator.comparing(Order::status)); // within one status, the date order is preserved
Sorting by column in a UI relies on exactly this. If you write your own sort, or use a non-stable path (say, repeated poll from a PriorityQueue), the order of equal elements "jumps" every time, and the user files it as a bug.
One more subtle point: if a comparator breaks the contract, TimSort may notice and throw an IllegalArgumentException. That is a different topic, but it comes from this same algorithm.
Sign up to mark studied questions and save your progress.