I've got a large array of primitive types (double). How do I sort the elements in descending order?
Unfortunately the Java API doesn't support sorting of primitive types with a Comparator.
One workaround would be to sort and then reverse:
double[] array = new double[1048576];
...
Arrays.sort(array);
// reverse the array
for (int i = 0; i < array.length / 2; i++) {
// swap the elements
double temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
This is slow - particularly if the array is already sorted quite well.
What's a better alternative?
Your algorithm is correct. But we can do optimization as follows: While reversing, You may try keeping another variable to reduce backward counter since computing of array.length-(i+1) may take time! And also move declaration of temp outside so that everytime it needs not to be allocated
Understand it's a very old post but I stumbled upon a similar problem trying to sort primitive int arrays, so posting my solution. Suggestions/comments welcome -
There's been some confusion about
Arrays.asList
in the other answers. If you saythen you'll have a List with 1 element. The resulting List has the double[] array as its own element. What you want is to have a
List<Double>
whose elements are the elements of thedouble[]
.Unfortunately, no solution involving Comparators will work for a primitive array.
Arrays.sort
only accepts a Comparator when being passed anObject[]
. And for the reasons describe above,Arrays.asList
won't let you make a List out of the elements of your array.So despite my earlier answer which the comments below reference, there's no better way than manually reversing the array after sorting. Any other approach (such as copying the elements into a
Double[]
and reverse-sorting and copying them back) would be more code and slower.Java Primitive includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:
If you're using Maven, you can include it with:
When you pass
false
as the third argument tosort
, it uses an unstable sort, a simple edit of Java's built-in dual-pivot quicksort. This means that the speed should be close to that of built-in sorting.Full disclosure: I wrote the Java Primitive library.
I am not aware of any primitive sorting facilities within the Java core API.
From my experimentations with the D programming language (a sort of C on steroids), I've found that the merge sort algorithm is arguably the fastest general-purpose sorting algorithm around (it's what the D language itself uses to implement its sort function).