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);
}
- Why create aux?
- How is the sort ever working if the code sorts aux?
- Isn’t this a waste of resources to clone the array before sorting?
Because the
mergeSortmethod requires a source and destination array.Because the
mergeSortmethod sorts fromauxtoaNo it is not … using that implementation of
mergeSort. Now if thesortreturned 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 thatamust 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
mergeSortmethod, 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.