7

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

John Hendrik
  • 661
  • 1
  • 7
  • 20
  • 5
    In what way is this sorted? Looks like just zipped together (in the respective original order) – Thilo Dec 19 '12 at 12:09

2 Answers2

8
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];
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    First time I have ever seen `i != last`. Any reason for this over the more idiomatic `i < last`? – Thilo Dec 19 '12 at 12:10
  • +1. Even though the argument does not seem to apply when the iteration counter is locally scope to just the loop. But probably a useful habit to get into for other situations (like in Javascript which does not have block-scope). – Thilo Dec 20 '12 at 00:23
  • 1
    I actually thought about doing this myself a couple of times, but was always worried that if for some reason the counter "skips ahead" too far, making me "miss the exit", then I end up with a practically infinite loop. – Thilo Dec 20 '12 at 00:25
2

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);
  }
}
weston
  • 54,145
  • 21
  • 145
  • 203