29

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?

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Only thing is this takes a copy of the array and so uses O(n) extra storage as per Collections.sort.
In Java 7 it doesn't take a copy. I haven't checked Java 6.
Interesting. I'm actually pretty surprised they've changed the behaviour to return the underlying array; can imagine this would cause lots of subtle bugs for people upgrading from Java 6.
Arrays.sort() doesn't return anything. The question is whether it copies the array before sorting it.
In Java 8 Collections.sort calls sort on the list, so it's up to the list implementation. ArrayList calls Arrays.sort with its element array, so that is still in place.
2

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)

1 Comment

you can do copy-pasta of the heapsort described here, using ArrayList instead of array: [link]en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Heapsort)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.