Logic:
While both array pointers are less than array lengths, Compare two first elements of the two arrays. If first element of first array is bigger
than first element of 2nd array , then move to 2nd element of 2nd array.
Again compare 2nd element of 2nd array to first element of 1st array. If the 2nd element of 2nd array is bigger than 1st element of first array, then move to 2nd element of 1st array.
If both are equal, print , and move to next elements of both arrays.
public class Arry
{
public static void main(String[] args)
{
int FirstArray[] = { 11, 23, 44, 65, 87, 98 };
int SecondArray[] = { 2, 23, 44, 65, 66 , 98 };
SortedArray ref= new SortedArray();
ref.getCommon(FirstArray, SecondArray);
}
}
class SortedArray
{
void getCommon(int[] First, int[] Second) {
int i = 0, j = 0;
System.out.println("Common array elements are : ");
while (i < First.length && j < Second.length)
{
if (First[i] > Second[j])
{
j++;
}
else if (Second[j] > First[i])
{
i++;
}
else
{
System.out.println(First[i]);
i++;
j++;
}
}
}
}
Copyright QA Friend Software Testing. All rights reserved.