Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine and sort two arrays of different length in Java

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

like image 915
John Hendrik Avatar asked Dec 19 '12 12:12

John Hendrik


2 Answers

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];
}
like image 105
Sergey Kalinichenko Avatar answered Nov 20 '22 16:11

Sergey Kalinichenko


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 ifs.

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);
  }
}
like image 40
weston Avatar answered Nov 20 '22 18:11

weston