patternjavaModerate
Merging sorted arrays
Viewed 0 times
sortedarraysmerging
Problem
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;Solution
Generally, you should do what you can not to throw an exception - it is slow and it looks bad.
In this case, you should go with:
Exceptions, as the name implies, suggest an exceptional condition in which the application is. In your case, it's just the algorithm's termination point - a point which you want to reach. It's not exceptional, it's desired.
Also, I don't think there ever is a good excuse to explicitly catch a
In this case, you should go with:
if (fstIndex<fst.length){
fstIndexValue = fst[fstIndex];
} else {
System.arraycopy(snd, sndIndex, result, fstIndex + sndIndex, snd.length - sndIndex);
break;
}Exceptions, as the name implies, suggest an exceptional condition in which the application is. In your case, it's just the algorithm's termination point - a point which you want to reach. It's not exceptional, it's desired.
Also, I don't think there ever is a good excuse to explicitly catch a
java.lang.ArrayIndexOutOfBoundsException - if your code is throwing it, then you're doing something else wrong (namely, missing appropriate checks).Code Snippets
if (fstIndex<fst.length){
fstIndexValue = fst[fstIndex];
} else {
System.arraycopy(snd, sndIndex, result, fstIndex + sndIndex, snd.length - sndIndex);
break;
}Context
StackExchange Code Review Q#90327, answer score: 12
Revisions (0)
No revisions yet.