Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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?

like image 379
NPE Avatar asked Nov 02 '11 12:11

NPE


3 Answers

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.

like image 170
Peter Lawrey Avatar answered Sep 19 '22 20:09

Peter Lawrey


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)

like image 31
soulcheck Avatar answered Sep 19 '22 20:09

soulcheck


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.

like image 45
GullerYA Avatar answered Sep 23 '22 20:09

GullerYA