I got a huge array of double types. How can I sort elements in descending order?
The Java API does not support the primitive type (like double) sorrting with a comparator. First approach that I had was
double[] array = new double[1048576];
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
But, boxing each primitive is way too slow and creates a lot of GC pressure. Another approach that I cam up with is to sort first and then reverse it
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 approach is also slow. What is a better way to solve this problem?