Merge Two Arrays In C++
Code snippet for how to Merge Two Arrays In C++ with sample and detail explanation
Merging two arrays in C++ is an important skill to understand as it can be used in various programming scenarios like sorting data. In this article, we will look into a simple technique for merging two arrays using C++.
Code Snippet: Merge Two Arrays in C++
#include<iostream>
using namespace std;
void mergeArrays(int arr1[], int arr2[], int n1, int n2, int arr3[])
{
int i = 0, j = 0, k = 0;
while (i<n1 && j <n2)
{
if (arr1[i] < arr2[j])
arr3[k++] = arr1[i++];
else
arr3[k++] = arr2[j++];
}
while (i < n1)
arr3[k++] = arr1[i++];
while (j < n2)
arr3[k++] = arr2[j++];
}
int main()
{
int arr1[] = {1, 3, 5, 7};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {2, 4, 6, 8};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int arr3[n1+n2];
mergeArrays(arr1, arr2, n1, n2, arr3);
cout << "Array after merging" <<endl;
for (int i=0; i < n1+n2; i++)
cout << arr3[i] << " ";
return 0;
}
Code Explanation: Merge Two Arrays in C++
In this C++ code snippet, we work on a simple method to merge two arrays.
-
First, we have the function
mergeArray
which mergesarr1[]
andarr2[]
intoarr3[]
. Here,n1
is the size ofarr1[]
,n2
is the size ofarr2[]
, andarr3[]
is the final array which will contain all the elements of botharr1[]
andarr2[]
in sorted order. -
The
while
loop is used to select the smaller element fromarr1[i]
andarr2[j]
and place it inarr3[k]
. We increase the index âkâ ofarr3[]
and the index of the array from which the element was chosen. -
The next two
while
loops are used for adding any remaining elements inarr1[]
orarr2[]
toarr3[]
after the firstwhile
loop breaks. -
In the
main
function, we define two arraysarr1[]
andarr2[]
and calculate their sizesn1
andn2
respectively. -
We then define the array
arr3[]
with a size equal to the sum ofn1
andn2
. -
After merging, we print the elements of
arr3[]
. The printed array will have the combined elements ofarr1[]
andarr2[]
in a sorted order.
In conclusion, this code provides a simple yet effective way to merge two arrays in C++. Through understanding and practicing this, you can further your understanding of how data manipulation works in C++.