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.
The first approach that probably comes to mind is to convert it to a list of objects (boxing):
double[] array = new double[1048576];
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
However, boxing each primitive in the array is too slow and causes a lot of GC pressure!
Another approach 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 approach is also slow - particularly if the array is already sorted quite well.
What's a better alternative?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)