-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy patharray_intersection.cpp
78 lines (62 loc) · 1.15 KB
/
array_intersection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<iostream>
#include <algorithm>
using namespace std;
printCommonArray(int c[], int n)
{
cout<<"[";
for(int i=0; i<n; i++)
{
if(i==n-1)
{
cout<<c[i];
}
else
{
cout<<c[i]<<", ";
}
}
cout<<"]";
}
void printIntersection(int a[], int b[], int n)
{
int k=0;
int common[n]={0};
int a_length=n;
int b_length=n;
for(int i=0; i<a_length; i++)
{
int j=0;
while(j<b_length)
{
if(a[i]==b[j])
{
common[k++]=a[i];
//then swap with the last element and reduce array size by 1 and check till that alone
swap(b[j],b[b_length-1]);
b_length=b_length-1;
break;
}
j++;
}
}
//sort common array
sort(common, common+k);
printCommonArray(common, k);
}
int main()
{
int n;
cin>>n;
int a[n], b[n];
for(int i=0; i<n; i++)
{
cin>>a[i];
}
for(int i=0; i<n; i++)
{
cin>>b[i];
}
int c[n];
printIntersection(a,b,n);
return 0;
}