In Java's standard library, is there a method that would allow one to sort an ArrayList
in place, i.e. using O(1)
extra storage?
Collections.sort(List<T>)
does not fulfil this requirement since it
dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array.
If there's nothing in the standard library, what third-party libraries can be used to do this?
You can extract the underlying array (e.g. reflection) and perform a Arrays.sort(array, 0, list.size()) on it.
Java 7 does not copy the array in Arrays.sort() before sorting the array. In Java 6 it does which means that Collections.sort() in Java 6 actually copies the underlying array TWICE to perform the sort.
Collections.sort()
was made to work with any List implementation, and that's why it's not working in place (merging LinkedList in place is difficult and sacrifices stability).
If you are really worried about sorting in-place you'll have to roll out your own sort funcion. It's not really worth your time unless your List is very long.
Arrays.sort(Object[])
does the same mergesort and is called internally by Collections.sort()
(at least in openjdk)
As of Java 8 List
interface has default void sort(Comparator<? super E> c)
API, using which you can sort an instance in place.
The list must be modifiable, iterable and its elements comparable to each other.
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