I am looking for a solution for my 'problem', that isn't an ugly hack.
In my Java code I have two arrays, both of an unknown length (so they will probably be of different length). I would like to sort them like this:
Array A: {1, 2, 3, 4, 5}
Array B: {6, 7, 8}
New Array: {1, 6, 2, 7, 3, 8, 4, 5}
Is there a nice way to accomplish this?
Thanks
int[] res = new int[a.length + b.length];
int p = 0;
int last = Math.max(a.length, b.length);
for (int i = 0 ; i != last ; i++) {
if (i < a.length) res[p++] = a[i];
if (i < b.length) res[p++] = b[i];
}
If it is likely that there are many more in one array than the other, it should be faster to zip the first part and then bulk copy the rest using System.arrayCopy
. It also simplifies dasblinkenlight's for
loop by removing the if
s.
int[] res = new int[a.length + b.length];
int p = 0;
//zip what we can
int last = Math.min(a.length, b.length);
for (int i = 0; i != last; i++) {
res[p++] = a[i];
res[p++] = b[i];
}
//now add the remaining
int aRemain = a.length - last;
if(aRemain > 0) {
System.arrayCopy(a, last, res, p, aRemain);
}
else
{
int bRemain = b.length - last;
if(bRemain > 0) {
System.arrayCopy(b, last, res, p, bRemain);
}
}
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