OneBite.Dev - Coding blog in a bite size

Merge Two Arrays Together In C++

Code snippet for how to Merge Two Arrays Together In C++ with sample and detail explanation

Combining two arrays into one within the C++ programming language is a task of fundamental importance, and a basic understanding of this operation can prove indispensable. This article breaks down a simple code snippet that performs this function and meticulously explains how each component works.

Code Snippet: Merging Two Arrays in C++

Here is a small and straightforward code snippet regarding how to 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: ";
    for (int i=0; i < n1+n2; i++)
        cout << arr3[i] << " ";
    return 0;
}

Code Explanation: Merging Two Arrays in C++

Let’s walk through this code a step at a time.

  • Firstly, we include the iostream library to enable input/output operations in C++ and define the standard namespace ‘std’ to save typing time and avoid naming conflicts.

  • The function ‘mergeArrays’ is defined with five parameters: two arrays ‘arr1’ and ‘arr2’, two integers ‘n1’ and ‘n2’ that denote the size of the respective arrays, and the third array ‘arr3’ where the merged array will be formed.

  • In the function ‘mergeArrays’, three variables ‘i’, ‘j’, and ‘k’ are initialized at 0. They represent indices for ‘arr1’, ‘arr2’, and ‘arr3’ respectively.

  • The first while loop compares elements from both ‘arr1’ and ‘arr2’, picking the smaller of the two elements and adding it to ‘arr3’. The chosen element’s array index and the merged array index are then incremented.

  • The second and third while loops are executed when one of the original arrays has remaining elements after all elements of the other array have been merged. These leftover elements are directly added to ‘arr3’.

In the main function:

  • Two integer arrays arr1 and arr2 are defined and their sizes, n1 and n2, are determined using the ‘sizeof()’ operator.

  • The third array arr3 is declared with a length equal to the sum of n1 and n2.

  • The function ‘mergeArrays’ is then called with the arrays and sizes as arguments.

  • Finally, a for loop is used to print every element in the merged array ‘arr3’ to verify that the arrays have been effectively combined.

This way, the code efficiently handles the task of merging two arrays in C++.

c-plus-plus