简体   繁体   中英

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

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM