Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

computer science c++ 6. The union of two bags is a new bag containing the combin

ID: 3788015 • Letter: C

Question

computer science c++

6. The union of two bags is a new bag containing the combined contents of the original two bags. Design and specify a method union for the ADT bag that returns as a new bag the union of the bag receiving the call to the method and the bag that is the method’s one argument. Include suf cient comments to fully specify the method. Note that the union of two bags might contain duplicate items. For example, if object x occurs ve times in one bag and twice in another, the union of these bags contains x seven times. Speci cally, suppose that bag1 and bag2 are bags; bag1 contains the strings a , b , and c ; and bag2 contains the strings b , b , d , and e . The expression bag1.union(bag2) returns a bag containing the strings a , b , b , b , c , d , and e . Note that union does not affect the contents of bag1 and bag2

Explanation / Answer

#include<stdio.h>

int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n)
{
   if (arr1[i] < arr2[j])
   printf(" %d ", arr1[i++]);
   else if (arr2[j] < arr1[i])
   printf(" %d ", arr2[j++]);
   else
   {
   printf(" %d ", arr2[j++]);
   printf(" %d ", arr1[i++]);
   }
}


while(i < m)
printf(" %d ", arr1[i++]);
while(j < n)
printf(" %d ", arr2[j++]);
}

int main()
{
int bag1[] = {1, 2, 4, 5, 6};
int bag2[] = {2, 3, 5, 7};
int m = sizeof(bag1)/sizeof(bag1[0]);
int n = sizeof(bag2)/sizeof(bag2[0]);
printUnion(bag1, bag2, m, n);
getchar();
return 0;
}