Merging Arrays
Merging arrays involves combining two or more arrays into a single array. This operation is useful when you need to combine related data or manipulate arrays in different ways. In C++, you can merge arrays using the mergeArrays
function.
Here's an example of merging two sorted arrays in C++:
1#include <iostream>
2#include <algorithm>
3using namespace std;
4
5void printArray(int arr[], int size) {
6 for (int i = 0; i < size; i++) {
7 cout << arr[i] << " ";
8 }
9 cout << endl;
10}
11
12void mergeArrays(int arr1[], int size1, int arr2[], int size2, int result[]) {
13 // Merge logic
14}
15
16int main() {
17 int arr1[] = {1, 3, 7, 9};
18 int size1 = sizeof(arr1) / sizeof(arr1[0]);
19
20 int arr2[] = {2, 4, 6, 8};
21 int size2 = sizeof(arr2) / sizeof(arr2[0]);
22
23 int result[size1 + size2];
24
25 cout << "Array 1: ";
26 printArray(arr1, size1);
27
28 cout << "Array 2: ";
29 printArray(arr2, size2);
30
31 mergeArrays(arr1, size1, arr2, size2, result);
32
33 cout << "Merged Array: ";
34 printArray(result, size1 + size2);
35
36 return 0;
37}
In the code snippet above, we have two sorted arrays: arr1
and arr2
. We want to merge them into a single sorted array. We define the function mergeArrays
, which takes the two arrays, their respective sizes, and an empty result array as parameters.
The mergeArrays
function uses a two-pointer approach to merge the arrays. It compares elements from both arrays and adds the smaller element to the result array. The function continues until all elements from both arrays have been processed.
After merging, the resulting array contains all elements from arr1
and arr2
in sorted order. In the example, the output will be:
Array 1: 1 3 7 9 Array 2: 2 4 6 8 Merged Array: 1 2 3 4 6 7 8 9
Merging arrays is a common operation when working with data that is spread across multiple arrays and needs to be combined for further processing. It is especially useful when dealing with sorted arrays, as merging can be done efficiently without the need for additional sorting.
You can experiment further by merging arrays of different sizes or unsorted arrays. The mergeArrays
function can be modified to accommodate various merge logics and requirements.
xxxxxxxxxx
}
using namespace std;
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void mergeArrays(int arr1[], int size1, int arr2[], int size2, int result[]) {
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2) {
if (arr1[i] <= arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < size1) {
result[k++] = arr1[i++];
}
while (j < size2) {
result[k++] = arr2[j++];
}