144 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:
- Two unsorted arrays,
arr1
andarr2
, are defined. - The sizes of
arr1
andarr2
are calculated using thesizeof
operator to determine the number of elements in each array. - An array named
mergedArray
is created with a size equal to the sum of the sizes ofarr1
andarr2
. - Elements from
arr1
are copied tomergedArray
using afor
loop. - Elements from
arr2
are copied tomergedArray
starting at the position after the last element ofarr1
. - 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.