Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
Stephen Avatar asked May 13 '11 02:05

Stephen


People also ask

What is the best way to sort an array in Java?

Collections.sort() works for objects Collections like ArrayList, LinkedList, etc. Using the reverse order method: This method will sort the array in the descending. In Java Collections class also provides the reverseOrder() method to sort the array in reverse-lexicographic order.

Which is the most efficient sorting algorithm in Java?

Quicksort. Quicksort is one of the most efficient sorting algorithms, and this makes of it one of the most used as well. The first thing to do is to select a pivot number, this number will separate the data, on its left are the numbers smaller than it and the greater numbers on the right.

How do you sort a big number array with limited memory?

Solution 1: step 1: Read M from the file and write it into a temp buffer. step 2: Sort (you should use in-place sorting algorithm, like QuickSort,HeapSort) the values. step 3: Create a temp file and write the buffer into the temp file.

Where is an array sorted in memory in Java?

Memory is allocated in Heap are for the Array in Java. In Java reference types are stored in the Heap area. As arrays are also reference types, (they can be created using the “new” keyword) they are also stored in the Heap area.


2 Answers

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

like image 187
dlev Avatar answered Oct 20 '22 00:10

dlev


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.

like image 24
Dante May Code Avatar answered Oct 20 '22 00:10

Dante May Code