C++ Program to Merge Two Arrays

«
»

This is a C++ Program to Merge Two Arrays in Order.

Problem Description

An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. This operation is used to merge two one-dimensional arrays into a third one-dimensional array.

We are given two arrays with their elements and we need to merge these two arrays such that the third array has all the elements of the first and second array with an array being in a sorted state.

Methods for this operation:
To perform this operation we can have two approaches one is Naive Approach i.e. a general approach with time complexity O(n1 * n2) where n1 and n2 are the sizes of the two array. Other is the Merge Sort Algorithm where with the help of Merge() function we will perform the operation with time complexity O(n1 + n2).

Approach One:
Naive Approach with time complexity O(n1 * n2)
Create third array of size n1 + n2.
Copy all n1 elements of the first array to the third array.
Traverse second array and one by one insert elements of the third array to the first array. This step takes O(n1 * n2) time.
Approach Two:
Merge Sort Algorithm with time complexity O(n1 + n1)
Create the third array of size n1 + n2.
Traverse first array and second array simultaneously.
Pick smaller of current elements in first array and second array, copy this smaller element to next position in the third array and move ahead in the third array and the array whose element is picked.
If there are remaining elements in the first array or second array, copy them also in the third array.

Here, we will use a Merge Sorting Algorithm to solve our problem.

Expected Input and Output

Case 1. Both the arrays have unsorted elements.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If the first array has elements = {3, 6, 1}
and second array has elements = {5, 2, 11, 16, 9},
then the output array will be = {1, 2, 3, 5, 6, 9, 11, 16}

Case 2. Both arrays are sorted in ascending order.

If the first array has elements = {2, 4, 6, 8}
and the second array has elements = {1, 3, 5, 7, 9, 11},
then the output array will be = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11}

Case 3. Both the arrays are sorted in descending order.

If the first array contains elements as = {9, 6, 5, 3, 1}
and the second array contains elements as = {21, 14, 9, 4},
then the output array will have elements {1, 3, 4, 5, 6, 9, 9, 14, 21}
Problem Solution

1. Create an array array3[ ] of size n1 + n2.
2. Traverse array1[ ] and array2[ ] simultaneously.
3. Pick smaller of current elements in array1[ ] and array2[ ], copy this smaller element to next position in array3[ ] and move ahead in array3[ ] and the array whose element is picked.
4. If there are remaining elements in array1[ ] or array2[ ], copy them also in array3[ ].

Program/Source Code

Here is the source code of the C++ Program to Merge Two Arrays in Order. The program is successfully compiled and tested using Codeblocks gnu/GCC compiler on Windows 10. The program output is also shown below.

advertisement
  1. /* C++ Program to Merge Two arrays */
  2. #include <bits/stdc++.h>
  3. #define N 100
  4. using namespace std;
  5. class merge_Array {
  6. public:
  7.     // Merge() function will merge the elements of array1 and array2 in array3. 
  8.     void Merge(int array1[N], int array2[N], int array3[N], int n1, int n2)
  9.     {
  10.         int i = 0, j = 0, k = 0;
  11.         // Traverse both array.
  12.         while (i < n1 && j < n2)
  13.         {
  14.             /* if element of array1 is smaller then 
  15.              * copy the element of array1 in array3
  16.              */
  17.             if (array1[i] < array2[j])
  18.             {
  19.                 array3[k++] = array1[i++];
  20.             }
  21.             /* if element of array2 is small then
  22.              * copy the element of array2 in array3
  23.              */
  24.             else
  25.             {
  26.                 array3[k++] = array2[j++];
  27.             }
  28.         }
  29.         // Copy remaining elements of first array.
  30.         while (i < n1)
  31.         {
  32.             array3[k++] = array1[i++];
  33.         }
  34.         // Copy remaining elements of second array
  35.         while (j < n2)
  36.         {
  37.             array3[k++] = array2[j++];
  38.         }
  39.     }
  40. };
  41. /*
  42.  * Main function
  43.  */
  44. int main()
  45. {
  46.     merge_Array ma;
  47.     int n1, n2, n3;
  48.     int i;
  49.     int A[N], B[N], C[N];
  50.     cout << "Enter the size of First array:\n";
  51.     cin >> n1;
  52.     cout << "\nEnter the elements of First array:\n";
  53.     for (i = 0; i < n1; i++)
  54.         cin >> A[i];
  55.     cout << "\nEnter the size of Second array:\n";
  56.     cin >> n2;
  57.     cout << "\nEnter the elements of Second array:\n";
  58.     for (i = 0; i < n2; i++)
  59.         cin >> B[i];
  60.     // Sorting first array
  61.     sort(A, A + n1);
  62.     // Sorting second array 
  63.     sort(B, B + n2);
  64.     cout << "\nElements of First sorted array:\n";
  65.     for (i = 0; i < n1; i++)
  66.         cout << A[i] << " ";
  67.     cout << "\nElements of Second sorted array:\n";
  68.     for (i = 0; i < n2; i++) {
  69.         cout << B[i] << " ";
  70.     }
  71.     ma.Merge(A, B, C, n1, n2);
  72.     cout << "\nElements after Merging Arrays:\n";
  73.     for (i = 0; i < (n1 + n2); i++) {
  74.         cout << C[i] << " ";
  75.     }
  76.     return 0;
  77. }
Program Explanation

1. Create a class merge_Array with Merge() function.
2. Get the input from the user for the size of the two arrays and the elements of the array also.
3. Create an object of class merge_Array i.e. ma.
4. Call sort() function to sort the two arrays.
5. Now display the two sorted array on the screen.
6. Call Merge() function through the object of class merge_Array.
7. For first while loop, traverse first array and second array simultaneously. Pick smaller of current elements in first array and second array, copy this smaller element to next position in the third array and move ahead in the third array and the array whose element is picked.
8. For second and third while loop, if there are remaining elements in the first array or second array, copy them also in the third array.
9. Return to the main function.
10. Print the final merged array in the main function.

Runtime Test Cases
Case 1 (Both the arrays have unsorted elements):
   Enter the size of First array:
   3
 
   Enter the elements of First array:
   3 6 1
 
   Enter the size of Second array:
   5
 
   Enter the elements of Second array:
   5 2 11 16 9
 
   Elements of First sorted array:
   1 3 6
   Elements of Second sorted array:
   2 5 9 11 16
   Elements after Merging Arrays:
   1 2 3 5 6 9 11 16
 
Case 2 (Both the arrays have sorted elements in ascending order):
   Enter the size of First array:
   4
 
   Enter the elements of First array:
   2 4 6 8
 
   Enter the size of Second array:
   6
 
   Enter the elements of Second array:
   1 3 5 7 9 11 
 
   Elements of First sorted array:
   2 4 6 8
   Elements of Second sorted array:
   1 3 5 7 9 11
   Elements after Merging Arrays:
   1 2 3 4 5 6 7 8 9 11
 
Case 3 (Both the arrays have sorted elements in descending order):
   Enter the size of First array:
   5
 
   Enter the elements of First array:
   9 6 5 3 1
 
   Enter the size of Second array:
   4
 
   Enter the elements of Second array:
   21 14 9 4
 
   Elements of First sorted array:
   1 3 5 6 9
   Elements of Second sorted array:
   4 9 14 21
   Elements after Merging Arrays:
   1 3 4 5 6 9 9 14 21

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.