c-plus-plus
  1. c-plus-plus-merge-two-unsorted-arrays

Merge two unsorted arrays

In this program, we will merge two unsorted arrays into a new array using C++.

Syntax

#include<iostream>
using namespace std;

int main() {
    //declare and initialize arrays
    int arr1[] = {9, 7, 2, 5};
    int n1 = sizeof(arr1)/sizeof(arr1[0]);

    int arr2[] = {4, 8, 1, 6};
    int n2 = sizeof(arr2)/sizeof(arr2[0]);

    //declare a new array to store the merged array
    int mergedArr[n1+n2];

    //copy elements of arr1 and arr2 into the merged array
    for(int i=0; i<n1; i++) {
        mergedArr[i] = arr1[i];
    }

    for(int j=0; j<n2; j++) {
        mergedArr[n1+j] = arr2[j];
    }

    //print the merged array
    cout<<"Merged Array : ";
    for(int i=0; i<n1+n2; i++) {
        cout<<mergedArr[i]<<" ";
    }

    return 0;
}

Example

Suppose we have two unsorted arrays of integers:

arr1 = [9, 7, 2, 5]
arr2 = [4, 8, 1, 6]

We want to merge these two arrays into a single array and display the merged array.

Output

Merged Array : 9 7 2 5 4 8 1 6

Explanation

In this program, we have declared two unsorted arrays arr1 and arr2 containing four integers each. We have then declared a new array mergedArr to store the merged array.

We have then used two for loops to copy the elements of arr1 and arr2 into mergedArr. The first for loop copies the elements of arr1 into mergedArr, and the second for loop copies the elements of arr2 into mergedArr, starting from the index n1 where n1 is the size of arr1.

Finally, we have printed the merged array mergedArr.

Use

This program can be used whenever there is a need to merge two unsorted arrays into a single array, for example, while merging two unsorted lists or sets of data.

Important Points

  • The size of the merged array should be equal to the sum of the sizes of the two unsorted arrays.
  • This program assumes that the two arrays are unsorted. If the arrays are sorted, a more efficient algorithm can be used for merging the sorted arrays.

Summary

In summary, this program demonstrates how to merge two unsorted arrays into a new array using C++. We have used two for loops to copy the elements of the two arrays into the merged array and then printed the merged array. This program can be used whenever there is a need to merge two unsorted arrays into a single array.

Published on: