Given two sorted arrays: A and B. The size of array A is La and the size of array B is Lb. How
Let's consider two sorted arrays: -
int[] array1 = {1,2,3,4,5,6,7,8};
int[] array2 = {2,4,8};
int i=0, j=0; //taken two pointers
While loop will run till both pointers reach up to the respective lengths.
while(i array2[j]) //if first array element is bigger then increment 2nd pointer
j++;
else if(array1[i] < array2[j]) // same checking for second array element
i++;
else { //if both are equal then print them and increment both pointers
System.out.print(a1[i]+ " ");
if(i==a1.length-1 ||j==a2.length-1) //one additional check for ArrayOutOfBoundsException
break;
else{
i++;
j++;
}
}
}
Output will be: -
2 4 8