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); }
- why create aux?
- how sort ever working if code sorts aux?
- 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
Post a Comment