简体   繁体   中英

Java: sorting an ArrayList in place

In Java's standard library, is there a method that would allow one to sort an ArrayList in place, ie 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 (eg 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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM