5 Dec 2017

Write a java program to find common elements from two given Arrays.


To find the common elements from given two array there will be following logic. Here is three method to solve this problem.


Method #1

public class CommonElements {
    public static void main(String[] args) {
        int arr1[] = {2, 3, 4, 5, 6};
        int arr2[] = {4, 6, 7, 8, 9};
                   System.out.print("Common elements are ::");
         for (int i = 0, j = 0;i < arr1.length && j < arr2.length;) {
                             if (arr1[i] == arr2[j])
                             {
               System.out.print(arr1[i]+", ");i++;j++;
            }
                             else if (arr1[i] > arr2[j])j++;
                             else  i++;
       }
    }
  }












Method #2

public class CommonElements {
    public static void main(String[] args) {
          int arr1[] = {2, 3, 4, 5, 6};
        int arr2[] = {4, 6, 7, 8, 9};
                   System.out.print("Common elements are ::");
                   for(int i=0;i<arr1.length;i++){
                             for(int j=0;j<arr2.length;j++){
                                      if(arr1[i]==arr2[j])
                                      {
                                                          System.out.print(arr1[i]+", ");
                                      }
                             }
                   }
          }
}

Output:



Method #3

import java.util.Arrays;
class  ArrayCommonElement
{
       public static void main(String[] args)
       {
              int[] a={15,20,5,8,12,4};
              int[] b={20,5,17,18,15};
              int len;
              int j=0,k=0;
              Arrays.sort(a);
              Arrays.sort(b);
              System.out.println("Common Elements are::");
              for(int i=0;j!=a.length && k!=a.length ;i++)
              {
                     if(a[j]==b[k])
                     {
                           System.out.print(a[j]+" " );
                           j++;k++;
                     }
                     else if(a[j]>b[k])
                           k++;
                     else if(a[j]<b[k])
                           j++;
              }
              System.out.println();
       }
}

Output