Link to home
Start Free TrialLog in
Avatar of niftyhawk
niftyhawk

asked on

Find common elements in two arrays

Hi..

I have the following program..

void FindCommonArrayElements(int a[], int sizeofa, int b[], int sizeofb)
{
   int c[10];
      for(int i=0;i<sizeofa;i++)
      {
            for(int j=0;j<sizeofb;j++)
            {
                  if(a[i] == b[j])
                  {
                        c[i] = a[i];
                  }
            }
      }
          for (int i = 0; i < sizeofa; i++)
           printf("c[%d] = %d\n", i, c[i]);
}

int main()
{
    int a[] = {1, 3, 5, 7, 9, 10, 11, 14, 15, 2};
      int b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      int sizeofa = sizeof(a)/sizeof(int);
      int sizeofb = sizeof(b)/sizeof(int);

      FindCommonArrayElements(a, sizeofa, b, sizeofb);

}

The output is correct but has some uninitialized values.. How to fix the program to get rid of the garbled data in between?

c[0] = 1
c[1] = 3
c[2] = 5
c[3] = 7
c[4] = 9
c[5] = 10
c[6] = -858993460
c[7] = -858993460
c[8] = -858993460
c[9] = 2

ASKER CERTIFIED SOLUTION
Avatar of lucky_james
lucky_james
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of niftyhawk
niftyhawk

ASKER

ah..yes it works now..thanks :)

void FindCommonArrayElements(int a[], int sizeofa, int b[], int sizeofb)
{
   int c[10];
   int k=0;
      for(int i=0;i<sizeofa;i++)
      {
            for(int j=0;j<sizeofb;j++)
            {
                  if(a[i] == b[j])
                  {
                        c[k] = a[i];
                        k++;
                  }
            }
      }
          for (int i = 0; i < k; i++)
           printf("c[%d] = %d\n", i, c[i]);
}

int main()
{
    int a[] = {1, 3, 5, 7, 9, 10, 11, 14, 15, 2};
      int b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      int sizeofa = sizeof(a)/sizeof(int);
      int sizeofb = sizeof(b)/sizeof(int);

      FindCommonArrayElements(a, sizeofa, b, sizeofb);

}
How can we improve the code so it runs faster than NLogN ?
your arrays are sorted. why dont you implement binary search in looking for the match?

this will prove much faster than current N^2 code complexity.