Stephen
Stephen

Reputation: 19944

How do I perform a memory-efficient array sort in java?

I'm wanting to sort a large array of Strings (notably File.list(), which I cannot externalise or reduce further) without using [much] extra memory.

Arrays.sort() says it does a merge sort, and wikipedia says that some implementations allocate the size of the original array for storing the sorted output. (This seems to be supported by the System.arraycopy reference in the method).

Is there an in-place sorting algorithm I can use instead which is memory efficient?

Upvotes: 7

Views: 3597

Answers (3)

Dante May Code
Dante May Code

Reputation: 11247

String is immutable in Java. Thus when the array of Strings in your question are duplicated, they do not require as much space as you expect. Actually, the overhead can be quite minimal.

In other words, Java's Arrays#sort() can be just fine for your solution. You may test the performance yourself.

For your title of the question, Ankit's answer and dlev's answer are just fine.

Upvotes: 5

Ankit Bansal
Ankit Bansal

Reputation: 5072

You can write an Heap Sort algorithm for in-place sorting.

Upvotes: 1

dlev
dlev

Reputation: 48596

quicksort is in-place and very fast. See here.

Upvotes: 6

Related Questions