Skip to content

Commit 31dc87d

Browse files
authored
Create 32 Intersection of two Array.cpp
1 parent 5fc026e commit 31dc87d

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include <iostream>
2+
using namespace std;
3+
struct Array
4+
{
5+
int *A;
6+
int size;
7+
int length;
8+
};
9+
10+
11+
void Display(struct Array* arr)
12+
{
13+
int i;
14+
cout << "The elements of the array is " << endl;
15+
for (i = 0; i < arr->length; i++)
16+
cout << arr->A[i]<<" ";
17+
}
18+
19+
20+
Array* Intersection(struct Array* arr1, struct Array* arr2)
21+
{
22+
Array* A = new Array;
23+
int n = arr1->length + arr2->length;
24+
A->A = new int[n];
25+
int i = 0;
26+
int j = 0;
27+
int k = 0;
28+
while (i < arr1->length && j < arr2->length)
29+
{
30+
if (arr1->A[i] < arr2->A[j])
31+
i++;
32+
else if (arr2->A[j] < arr1->A[i])
33+
j++;
34+
else {
35+
A->A[k++] = arr1->A[i++];
36+
j++;
37+
}
38+
}
39+
A->length = k;
40+
return A;
41+
}
42+
43+
44+
45+
int main()
46+
{
47+
struct Array arr;
48+
struct Array arr1;
49+
struct Array* arr2;
50+
51+
int no, i, no1;
52+
cout << "Enter the size of the array " << endl;
53+
cin >> arr.size;
54+
arr.A = new int[arr.size];
55+
cout << "Enter the length of the array " << endl;
56+
cin >> no;
57+
arr.length = 0;
58+
cout << "Enter the elements of the array" << endl;
59+
for (i = 0; i < no; i++)
60+
{
61+
scanf_s("%d", &arr.A[i]);
62+
}
63+
arr.length = no;
64+
65+
cout << "Enter the Size of the 2nd array " << endl;
66+
cin >> arr1.size;
67+
arr1.A = new int[arr1.size];
68+
cout << "Enter the length of the array " << endl;
69+
cin >> no1;
70+
arr1.length = 0;
71+
cout << "Enter the elements of the array " << endl;
72+
for (i = 0; i < no1; i++)
73+
{
74+
scanf_s("%d", &arr1.A[i]);
75+
}
76+
arr1.length = no1;
77+
78+
79+
80+
arr2 = Intersection(&arr, &arr1);
81+
Display(arr2);
82+
83+
84+
return 0;
85+
}

0 commit comments

Comments
 (0)