It is going out bounds on the first if statement even after I'm checking the values of j and k before incrementing
`int[] Merge(int[]a,int[]b){
int n=a.length+b.length;
int[] sol= new int[n];
int i=0,j=0,k=0;
while(i<n){
if(a[j]<b[k]){
sol[i]=a[j];
if(j<a.length)j++;
}
else if(b[k]<a[j]){
sol[i]=b[k];
if(k<b.length)k++;
}
i++;
}
return sol;
}`
I can't understand where the array is going out of bounds
Consider the case when either j=a.length-1 or k=b.length-1 then your if condition [ if(j<a.length)j++
; or if(k<b.length)k++;
]passes and makes j==a.length to true or k==b.length to true and the while loop access the array again when it throws ArrayIndexOutofBound exception. Also your code doesn't handle common elements in the array. Please check the correct code below
int[] Merge(int[]a,int[]b){
int n=a.length+b.length;
int[] sol= new int[n];
int i=0,j=0,k=0;
while(i<n){
if(a[j]<=b[k]){ // equality check handles common case
sol[i++]=a[j++];
if(j==a.length)
break;
}
else if(b[k]<a[j]){
sol[i++]=b[k++];
if(k==b.length)
break ;
}
}
if(j==a.length) {
while (k != b.length)
sol[i++]=b[k++];
}
if(k==b.length) {
while (j != a.length)
sol[i++]=a[j++];
}
return sol;
}
The problem is here:
if(j<a.length)j++;
Here when j = a.length - 1 then it will become a.length because of j++. Now, a[j] will be out of bounds because j = a.length. a[a.length] is always out bounds. The indexing starts from 0, so last index is a.length - 1.
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.