I'd like to know if it's ok to write like this or there is a better, prettier way to do this. The merging itself is ok. I'm more interested in dealing with the situation when one of the arrays is finished and I need to copy the rest of the other array to the result
array. I wrote it in a try
catch
block.
int[] result = new int[fst.length + snd.length];
int fstIndex = 0;
int fstIndexValue = 0;
int sndIndex = 0;
int sndIndexValue = 0;
while (fstIndex + sndIndex != result.length) {
try{
fstIndexValue = fst[fstIndex];
}catch( java.lang.ArrayIndexOutOfBoundsException e) {
System.arraycopy(snd, sndIndex, result, fstIndex + sndIndex, snd.length - sndIndex);
break;
}
try{
sndIndexValue = snd[sndIndex];
}catch( java.lang.ArrayIndexOutOfBoundsException e) {
System.arraycopy(fst, fstIndex, result, fstIndex + sndIndex, fst.length - fstIndex);
break;
}
if (fstIndexValue < sndIndexValue) {
result[fstIndex + sndIndex] = fst[fstIndex++];
} else {
result[fstIndex + sndIndex] = snd[sndIndex++];
}
}
return result;
fstIndex
andsndIndex
instead offirstIndex
andsecondIndex
? \$\endgroup\$