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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With