views:

611

answers:

4

Given two sorted arrays: A and B. The size of array A is La and the size of array B is Lb. How to find the intersection of A and B? If La is much bigger than Lb, then will there be any difference for the intersection finding algorithm?

+3  A: 

Use set_intersection as here. The usual implementation would work similar to the merge part of merge-sort algorithm.

Amit Kumar
+3  A: 

Since this looks like a HW...I'll give you the algorithm:

Let arr1,arr2 be the two sorted arrays of length La and Lb.
Let i be index into the array arr1.
Let j be index into the array arr2.
Initialize i and j to 0.

while(i < La and j < Lb) do

    if(arr1[i] == arr2[j]) { // found a common element.
        print arr[i] // print it.
        increment i // move on.
        increment j
    }
    else if(arr1[i] > arr2[j])
        increment j // don't change i, move j.
    else
        increment i // don't change j, move i.
end while
codaddict
@Down voter: Care to explain ?
codaddict
+1: Good answer
ArunSaha
+1  A: 
void Intersect()
{
    int la, lb;
    la = 5;
    lb = 100;
    int A[5];
    int i, j, k;
    i = j = k = 0;
    for (; i < 5; ++i)
        A[i] = i + 1;
    int B[100];
    for (; j < 100; ++j)
        B[j] = j + 2;
    int newSize = la < lb ? la : lb;
    int* C = new int[newSize];
    i = j = 0;
    for (; k < lb && i < la && j < lb; ++k)
    {
        if (A[i] < B[j])
            i++;
        else if (A[i] > B[j])
            j++;
        else
        {
            C[k] = A[i];
            i++;
            j++;
        }
    }
    for (k = 0; k < newSize; ++k)
        cout << C[k] << NEWLINE;
}
Rajendra Kumar Uppal
A: 

I think your best bet would be to use this technique. The payoff is immense. The best reasons for using this technique is sited here.

daramarak
1. It's not homework, 2. This is not an answer, keep commentary to comments.
Peter Alexander
@Poita_1. This question cannot be interpreted as anything else than homework no matter what setting the question is asked in. It is a trivial example of something basic that the person need to learn.2. This is an answer, as the technique I state will solve his/her problem.3. If the person asking have problems with this technique, my second link will tell him/her how to obtain useful information on stack overflow.
daramarak