





Finding if Arrays are disjoint or not using C
Finding if Arrays are disjoint or not in C
Here in this page we will discuss the program to find if arrays are disjoint or not in C programming language. Two arrays are said to be disjoint sets if they have no element in common. Equivalently, two disjoint sets are sets whose intersection is the empty set.

Here, in this page we will discuss the following methods, to check whether two given arrays are disjoint or not.
- Method 1 : Using two loops
- Method 2 : Using Sorting and merging
Method 1 :
- Run a loop from index 0 to n
- Run a nested loop from 0 to m
- Check if (arr1[i]==arr2[j]) return 0.
- Otherwise, return 1.
Method 1 : Code in C
#include<stdio.h> int disjoint(int arr1[], int arr2[], int n, int m){ for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(arr1[i]==arr2[j]){ return 0; } } } return 1; } int main(){ int arr1[] = {10, 20, 30, 67}; int arr2[] = {20, 90, 80, 77, 23}; int n = sizeof(arr1)/sizeof(arr1[0]); int m = sizeof(arr2)/sizeof(arr2[0]); if(disjoint(arr1, arr2, n, m)) printf("Yes"); else printf("No"); }
Output
No
Method 2 :
In this method sort both the arrays then using the process of merging compare the elements.
- Sort the arr1
- Then sort arr2
- Now, use the merge concept compare the elements of both the arrays.
Method 2 : Code in C
#include<stdio.h> int disjoint(int arr1[], int arr2[], int n, int m){ // Sort the given first array for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ if(arr1[i]>arr1[j]){ int temp = arr1[i]; arr1[i] = arr1[j]; arr1[j] = temp; } } } // Sort the given second array for(int i=0; i<m; i++){ for(int j=i+1; j<m; j++){ if(arr2[i]>arr2[j]){ int temp = arr2[i]; arr2[i] = arr2[j]; arr2[j] = temp; } } } // Check for same elements using merge like process int i = 0, j = 0; while (i < m && j < n) { if (arr1[i] < arr2[j]) i++; else if (arr2[j] < arr1[i]) j++; else /* if set1[i] == set2[j] */ return 0; } return 1; } int main(){ int arr1[] = {10, 20, 30, 67}; int arr2[] = {20, 90, 80, 77, 23}; int n = sizeof(arr1)/sizeof(arr1[0]); int m = sizeof(arr2)/sizeof(arr2[0]); if(disjoint(arr1, arr2, n, m)) printf("Yes"); else printf("No"); }
Output
No
February 15, 2022
print(“Enter the first arr”)
arr1=list(map(int,input(“1st–>”).split()))
print(“Enter the Second arr”)
arr2=list(map(int,input(“2nd–>”).split()))
sum=0
for i in arr1:
for j in arr2:
if i==j:
sum+=1
if sum>0:
print(“Are NOt disjoint”)
else:
print(“Are disjoint”)
#include
using namespace std;
int main(){
int n,m;
cout<<"Enter size of first array: "<>n;
int a[n];
cout<<"Enter size of second array: "<>m;
int b[m];
int k=0;
cout<<"Enter element of first array: "<<endl;
for(int i=0;i>a[i];
}
cout<<" Enter element of second array: "<<endl;
for(int i=0;i>b[i];
}
for(int i=0;i<n;i++){
for(int j=0;j0){
cout<<"It is not disjoint .";
}
else{
cout<<"It is disjoint .";
}
return 0;
}