Check if two given sets are disjoint?

Two sets are disjoint set when they have no common elements. In other words, if we get the intersection of two sets, then we will get null set.

The method is simple, in this algorithm, two sets are given. We assume that both sets are already sorted, items are compared between two sets. when there is a match, then it is not a disjoint set, when no items are matched, they are disjoint sets.

Input and Output

Input:
Two sets:
set1: {15, 12, 36, 21, 14}
set2: {7, 89, 56, 32}
Output:
Both sets are disjoint

Algorithm

isDisjoint(set1, set2)

Input: Two sets.

Output: True when both sets are disjoint.

Begin
   i1 := start of first set
   i2 := start of second set
   while i1 in set1 and i2 in set 2, do
      if set1[i1] 

Example

#include
#include
using namespace std;

bool isDisjoint(set set1, set set2) {
   set::iterator i1, i2;
   i1 = set1.begin(); i2 = set2.begin();            //initialize iterators with first element
   while(i1 != set1.end() && i2 != set2.end()) {         //when both set have some elements to check
      if(*i1  set1, set2;
   int n1, n2;
   cout >n1;

   while(n1 != set1.size()) {       //duplicate items will be discarded
      int item;
      cout > item;
      set1.insert(item);
   }

   cout >n2;
   while(n2 != set2.size()) {
      int item;
      cout > item;
      set2.insert(item);
   }

   if(isDisjoint(set1, set2))
      cout 

Output

Enter number of elements in set 1: 5
Enter element: 15
Enter element: 12
Enter element: 36
Enter element: 21
Enter element: 14
Enter number of elements in set 2: 4
Enter element: 7
Enter element: 89
Enter element: 56
Enter element: 32
Both sets are disjoint
Updated on: 2020-06-17T09:13:53+05:30

862 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements