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?
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.
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.
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.
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.
quicksort is in-place and very fast. See here.
String
is immutable in Java. Thus when the array of String
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With