OneBite.Dev - Coding blog in a bite size

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.

  1. First, we have the function mergeArray which merges arr1[] and arr2[] into arr3[]. Here, n1 is the size of arr1[], n2 is the size of arr2[], and arr3[] is the final array which will contain all the elements of both arr1[] and arr2[] in sorted order.

  2. The while loop is used to select the smaller element from arr1[i] and arr2[j] and place it in arr3[k]. We increase the index ‘k’ of arr3[] and the index of the array from which the element was chosen.

  3. The next two while loops are used for adding any remaining elements in arr1[] or arr2[] to arr3[] after the first while loop breaks.

  4. In the main function, we define two arrays arr1[] and arr2[] and calculate their sizes n1 and n2 respectively.

  5. We then define the array arr3[] with a size equal to the sum of n1 and n2.

  6. After merging, we print the elements of arr3[]. The printed array will have the combined elements of arr1[] and arr2[] 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++.

c-plus-plus