Benedikt Waldvogel Benedikt Waldvogel - 1 year ago 133
Java Question

Sort arrays of primitive types in descending order

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];
// 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?

Answer Source

Java Primitive includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:

double[] array = new double[1048576];
Primitive.sort(array, (d1, d2) ->, d1), false);

If you're using Maven, you can include it with:


When you pass false as the third argument to sort, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download