Computer Science, asked by hahaha3bar, 8 months ago

Consider two sorted integer arrays A and B in ascending order. We want two merge the two arrays to form a separate sorted array without violating the ascending order of the values. Implement the solution in C++ using primitive data types. What is the time complexity of populating the emerging array? guys i need your help please give me answer its urgent

Answers

Answered by mayank869931
1

Answer:

let's chat on whatsapp

Answered by cafatia2005
1

Answer:

// Merge arrA[0..n1-1] and arrB[0..n2-1] into

// arrC[0..n1+n2-1]

void mergeArrays(int arrA[], int arrB[], int n1,

                            int n2, int arrC[])

{

   int i = 0, j = 0, k = 0;

 

   // Traverse both array

   while (i<n1 && j <n2)

   {

       // Check if current element of first

       // array is smaller than current element

       // of second array. If yes, store first

       // array element and increment first array

       // index. Otherwise do same with second array

       if (arrA[i] < arrB[j])

           arrC[k++] = arrA[i++];

       else

           arrC[k++] = arrB[j++];

   }

 

   // Store remaining elements of first array

   while (i < n1)

       arrC[k++] = arrA[i++];

 

   // Store remaining elements of second array

   while (j < n2)

       arrC[k++] = arrB[j++];

}

 

// Driver code

int main()

{

   int arrA[] = {1, 3, 5, 7};

   int n1 = sizeof(arrA) / sizeof(arrA[0]);

 

   int arrB[] = {2, 4, 6, 8};

   int n2 = sizeof(arrB) / sizeof(arrB[0]);

 

   int arrC[n1+n2];

   mergeArrays(arrA, arrB, n1, n2, arrC);

 

   cout << "Array after merging" <<endl;

   for (int i=0; i < n1+n2; i++)

       cout << arrC[i] << " ";

 

   return 0;

}

OUTPUT:

Array after merging

1 2 3 4 5 6 7 8

Similar questions