4

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?
Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
  • Why are you asking these questions? You clearly have the source code in front of you, and the answers are obvious from just reading the javadoc comments for the `mergeSort` method. – Stephen C Nov 16 '10 at 01:41
  • @Stephen C: Your absolutely right. That's what happens when you post questions to SO at 3 in the morning (IST) instead of going to sleep. Anyway's good answers, I've learned from them. – Maxim Veksler Nov 16 '10 at 09:01

3 Answers3

2

Read the mergeSort source.

It's a non-inplace sort with two parameters (src and dest).
It sorts the dest parameter and uses the src parameter for reference.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Scroll down in that source file and look at how the recursive mergeSort works. I think it's a bit too involved to try to explain in a post on here so here's a good reference:

http://en.wikipedia.org/wiki/Merge_sort

JOTN
  • 6,120
  • 2
  • 26
  • 31