Web Toolbar by Wibiya

Pages

Tuesday, November 15, 2011

Find intersection of two arrays.

Solution #1: Intersection of two arrays means the set of elements which are present in both the arrays. The code below assumes that both the arrays are already sorted. Even if they are not, they can be sorted using any standard sorting algorithm like merge sort in O(n logn). The below code has a complexity of O(m+n) where 'm' and 'n' are the size of the arrays.

#include 
#include 

#define SIZE_A 100
#define SIZE_B 300

void intersection(int* A, int lenA, int* B, int lenB)
{
    int i=0;
    int j=0;

    while((i < lenA) && (j < lenB))
    {
        if(A[i] == B[j])
        {
            printf("%d\n", A[i]);
            i++;
            j++;
        }
        else if(A[i] < B[j])
        {
            i++;
        }
        else
        {
            j++;
        }
    }
}

int main()
{
    int A[SIZE_A];
    int B[SIZE_B];
    int i;

    for(i=0; i < SIZE_A; i++)
        A[i] = i*11;

    for(i=0; i < SIZE_B; i++)
        B[i] = i*22;

    intersection(A, SIZE_A, B, SIZE_B);

    return 0;
}

No comments: