I am currently trying to transcribe a mergesort algorithm from a pseudocode level to a working implementation in java. This is my code
public int[] merge(int a[], int b[]) {
int c[] = new int[a.length + b.length];
int i = 0, j = 0;
for (int k = 0; k < c.length; k++) {
if (a[i] <= b[j]) {
c[k] = a[i++];
} else {
c[k] = b[j++];
}
}
return c;
}
The pseudocode interpretation is correct to the best of my knowledge but it keeps returning an ArrayOutofBound Exception. Where did I get it all wrong.
a[a.length-1]<b[0]: you run through the entireaarray, incrementitoa.length, and then try to compare a non-existent element inawith the first element ofb. You need to actively check for the end of one array, and then just run through the other once that happens.