Why does Java's List.sort copy the list into an array before sorting, instead of sorting the list where it is?
Sorting algorithms index into their data, and get(i) on a linked list walks from one end, $O(n)$ per access, so sorting the list in place would take about $n^2 \log n$. Copying into an array ($O(n)$), sorting the array ($O(n \log n)$) and writing back with a list iterator ($O(n)$) keeps the total at $O(n \log n)$.
Since Java 8, Collections.sort(list) simply calls list.sort(null): null because no comparator is needed when the elements bring their own compareTo. The default List.sort then works in three passes:
- Copy all elements into an array with
toArray(), $O(n)$. - Sort that array with
Arrays.sort, $O(n \log n)$. - Walk the list with a
ListIteratorand overwrite each element with the next one from the sorted array, $O(n)$.
Two extra passes and a temporary array look wasteful, but they turn every element access of the sort into an $O(1)$ array access. An algorithm written against the List interface, calling get(i) and set(i, x), would be fine on an ArrayList and a disaster on a LinkedList, where each of those calls costs $O(n)$: an interface hiding an expensive operation. ArrayList skips the copying altogether: it overrides sort and sorts its internal array directly.
Go deeper:
List.sort (Java 21 API) โ the implementation requirement that spells out the copy-sort-write-back strategy.