In this article, we will see how you can merge two arrays in C++. The array is a collection of similar types of data items in a larger group. The array is used to store multiple similar types of values in a single variable.
Code:
In the below code, we will see how we can merge two arrays into a large single array in C++.
int main()
{
int arr1[] = { 4, 2, 3 };
int arr2[] = { 7, 8, 6 };
//Finding the aray length
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
// Creating new array by merging two arrays n1 & n2
int arr3[n1 + n2];
// Copy the elements from the first array
for (int i = 0; i < n1; i++)
arr3[i] = arr1[i];
// Copy the elements from the second array
for (int i = 0; i < n2; i++)
arr3[n1 + i] = arr2[i];
// Print the concatenated array
cout << "Merged Array: ";
for (int i = 0; i < n1 + n2; i++)
cout << arr3[i] << " ";
cout << endl;
return 0;
}
Output:
Merged Array: 4 2 3 7 8 6
Time Complexity: O(N+M), where N and M are the lengths of both arrays.
Auxiliary Space: O(N+M)