Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to sort an array without overwriting it

I want to sort an int[] array in Java, but store the sorted array as a new array instead of overwriting it.

The most obvious way to do this seems to be to create a copy of the array and then sort that new array, like so:

int[] a2 = new int[a.length];

for (int i = 0; i < this.length; i++) {
    a2[i] = a[i];
}

Arrays.sort(a2);

However, is there a faster way? Can we sort 'at the same time' as we copy the elements of the old array into the new one?

like image 588
hcaulf Avatar asked May 21 '15 11:05

hcaulf


1 Answers

You could use

int[] a2 = IntStream.of(a).sorted().toArray();

But I doubt it's faster than

int[] a2 = a.clone();
Arrays.sort(a2);

Regardless it's the same complexity, so don't expect more than a constant factor speedup.

like image 173
aioobe Avatar answered Oct 25 '22 18:10

aioobe