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


can please explain 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 sort ever working if code sorts aux?
  3. isn't waste of resources clone array before sorting?

1: why create aux?

because mergesort method requires source , destination array.

2: how sort ever working if code sorts aux?

because mergesort method sorts from aux to a

3: isn't waste of resources clone array before sorting?

no not ... using implementation of mergesort. if sort returned sorted array, doing clone (rather creating empty array) wasteful. api requires in-place sort, , means a must "destination". elements need copied temporary array "source".

if take @ mergesort method, see recursively partitions array sorted, merging backwards , forwards between source , destination arrays. work, need 2 arrays. presumably, sun / oracle have determined algorithm gives performance typical java sorting use-cases.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -