The Complexity of what I give is O(N*M + N)
.
Also note that it is Pseudocode C And that it provides distinct values.
eg.[1,1,1,2,2,4]
and [1,1,1,2,2,2,5]
Will return [1,2]
The Complexity is
N*M
cause of the for
loops
+ N
cause of the checking if it already exists in the ArrayCommon[]
(which is n
size in case Array2[]
contains data which duplicate Part of the Array1[]
Assuming N is the size of the smaller Array (N < M).
int Array1[m] = { Whatever };
int Array2[n] = { Whatever };
int ArrayCommon[n] = { };
void AddToCommon(int data)
{
//How many commons we got so far?
static int pos = 0;
bool found = false;
for(int i = 0 ; i <= pos ; i++)
{
//Already found it?
if(ArrayCommon[i] == data)
{
found = true;
}
}
if(!found)
{
//Add it
ArrayCommon[pos] = data;
pos++;
}
}
for(int i = 0 ; i < m ; i++)
{
for(int j = 0 ; j < n ; j++)
{
//Found a Common Element!
if(Array1[i] == Array2[j])
AddToCommon(Array1[i]);
}
}