Intersection of two integer arrays without using hash table

using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] A = { 1, 2, 3, 4, 3, 3 };
            int[] B = { 3, 4, 3 };
            int i, j, k;
            for (i = 0; i < A.Length; i++)
            {
                for (j = 0; j < i; j++)
                {
                    if (A[j] == A[i])
                    {
                        break;
                    }
                }
                if (j < i) //check if the break was due to a match
                {
                    continue;
                }
                // either i == j == 0 or it's a distinct element
                //Console.WriteLine(A[i]);
                k = 0;
                //i represents the first position of unique elements in the array
                for (j = i; j < A.Length; j++)
                {
                    if (A[i] != A[j])
                    {
                        continue;// until A[i] == A[j] or i == j
                    }
                    //Compare with all the repetitions of A[i] represented by A[j]
                    for (; k < B.Length; k++)
                    {
                        if (A[j] == B[k])
                        {
                            Console.WriteLine(A[i]);
                            k++;
                            break;// on the first match
                        }
                    }
                }
            }
        }
    }
}

Output
=======
3
3
4
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s