Search code examples
javaarrayssortingsun

Why Sun's Arrays.sort implementation creates a clone of the input array?


Can someone please explain the following code?

Source: Arrays.class,

public static <T> void sort(T[] a, Comparator<? super T> c) {
T[] aux = (T[])a.clone();
    if (c==null)
        mergeSort(aux, a, 0, a.length, 0);
    else
        mergeSort(aux, a, 0, a.length, 0, c);
}
  1. Why create aux?
  2. How is the sort ever working if the code sorts aux?
  3. Isn't this a waste of resources to clone the array before sorting?

Solution

  • 1: Why create aux?

    Because the mergeSort method requires a source and destination array.

    2: How is the sort ever working if the code sorts aux?

    Because the mergeSort method sorts from aux to a

    3: Isn't this a waste of resources to clone the array before sorting?

    No it is not ... using that implementation of mergeSort. Now if the sort returned a sorted array, doing a clone (rather than creating an empty array) would be wasteful. But the API requires it to do an in-place sort, and this means that a must be the "destination". So the elements need to copied to a temporary array which will be the "source".

    If you take a look at the mergeSort method, you will see that it recursively partitions the array to be sorted, merging backwards and forwards between its source and destination arrays. For this to work, you need two arrays. Presumably, Sun / Oracle have determined that this algorithm gives good performance for typical Java sorting use-cases.