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?
2
  • 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. Commented Nov 16, 2010 at 1: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. Commented Nov 16, 2010 at 9:01

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.