title: Sort large arrays of primitive types in descending order
body: <p>I've got a <strong>large</strong> array of primitive types (double).
  How do I sort the elements in <strong>descending order</strong>?</p>
  <p>Unfortunately the Java API doesn't support sorting of <strong>primitive</strong> types with a Comparator.</p>
  <p>The first approach that probably comes to mind is to convert it to a list of objects (boxing):</p>
  <pre><code>double[] array = new double[1048576];    
  Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
  </code></pre>
  <p>This solution is probably good enough for many (or even most) use cases but <strong>boxing</strong> each primitive in the array is <strong>too slow and causes a lot of GC pressure</strong> if the array is large!</p>
  <p>Another approach would be to sort and then reverse:</p>
  <pre><code>double[] array = new double[1048576];
  ...
  Arrays.sort(array);
  // reverse the array
  for (int i = 0; i &lt; array.length / 2; i++) {
       // swap the elements
       double temp = array[i];
       array[i] = array[array.length - (i + 1)];
       array[array.length - (i + 1)] = temp;
  }
     
  </code></pre>
  <p><strong>This approach can also be too slow</strong> if the array is already sorted quite well.</p>
  <p>What's a better alternative if the arrays are large and performance is the major optimization goal?</p>