In JDK 1.8, the first statement of the java.util.List#sort(Comparator)
method is the following:
Object[] a = this.toArray();
It's expensive to copy the list into an array, sort it, and reset every node of the list to the sorted value from the array.
It seems like it's possible not to copy values to a temporary array when sorting an ArrayList
. Am I right? If not, what guided the creators of the method?
The sort
in the java.util.List
interface is just the default implementation of the list sort.
ArrayList
overrides this default with a sort method which does sort its internal array directly.
For ArrayList, or other random access Lists, you may be correct.
However, Collections.sort supports any List implementation. For a LinkedList, for example, it would have been very expansive to swap elements during the sort (since finding the i'th element takes linear time).
Converting the List to an array, and setting the elements of the original List after the array is sorted adds a linear time component to the algorithm, which doesn't change the asymptotic running time of (O(nlog(n)))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With