Cover Image for C++ program to merge two unsorted arrays
139 views

C++ program to merge two unsorted arrays

Merging two unsorted arrays in C++ is a straightforward task. You can create a new array and copy elements from both arrays into it. Here’s a C++ program to merge two unsorted arrays:

C++
#include <iostream>

int main() {
    int arr1[] = {5, 9, 2, 8};
    int arr2[] = {3, 7, 1, 6};
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    int size2 = sizeof(arr2) / sizeof(arr2[0]);

    int mergedSize = size1 + size2;
    int mergedArray[mergedSize];

    // Copy elements from arr1 to mergedArray
    for (int i = 0; i < size1; ++i) {
        mergedArray[i] = arr1[i];
    }

    // Copy elements from arr2 to mergedArray
    for (int i = 0; i < size2; ++i) {
        mergedArray[size1 + i] = arr2[i];
    }

    // Print the merged array
    std::cout << "Merged Array: ";
    for (int i = 0; i < mergedSize; ++i) {
        std::cout << mergedArray[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this program:

  1. Two unsorted arrays, arr1 and arr2, are defined.
  2. The sizes of arr1 and arr2 are calculated using the sizeof operator to determine the number of elements in each array.
  3. An array named mergedArray is created with a size equal to the sum of the sizes of arr1 and arr2.
  4. Elements from arr1 are copied to mergedArray using a for loop.
  5. Elements from arr2 are copied to mergedArray starting at the position after the last element of arr1.
  6. The merged array is printed to the console.

When you run this program, it will merge the two unsorted arrays arr1 and arr2, and display the merged result. You can adjust the size and contents of arr1 and arr2 to fit your specific use case.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS