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?
I think the easiest solution is still:
As said by others before: using toList is additional effort, Arrays.sort(array,Collections.reverseOrder()) doesn't work with primitives and using an extra framework seems too complicated when all you need is already inbuild and therefore probably faster as well...
Sample code:
Guava has methods for converting primitive arrays to Lists of wrapper types. The nice part is that these lists are live views, so operations on them work on the underlying arrays as well (similar to
Arrays.asList()
, but for primitives).Anyway, each of these Lists can be passed to
Collections.reverse()
:Output:
...
By default order is ascending
To reverse the order
With numerical types, negating the elements before and after sort seems an option. Speed relative to a single reverse after sort depends on cache, and if reverse is not faster, any difference may well be lost in noise.
In Java 8, a better and more concise approach could be:
This would give the reversed array and is more presentable.
Input: [13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4]
Output: [100.4, 45.8, 21.09, 13.6, 9.12, 7.2, 6.02, 2.53]
I think it would be best not to re-invent the wheel and use Arrays.sort().
Yes, I saw the "descending" part. The sorting is the hard part, and you want to benefit from the simplicity and speed of Java's library code. Once that's done, you simply reverse the array, which is a relatively cheap O(n) operation. Here's some code I found to do this in as little as 4 lines: