Merging two sorted arrays involves combining the elements of both arrays into a new sorted array. Here's an example implementation of merging two sorted arrays in C:
```
#include <stdio.h>
void merge(int arr1[], int n1, int arr2[], int n2, int merged[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
merged[k] = arr1[i];
i++;
} else {
merged[k] = arr2[j];
j++;
}
k++;
}
while (i < n1) {
merged[k] = arr1[i];
i++;
k++;
}
while (j < n2) {
merged[k] = arr2[j];
j++;
k++;
}
}
int main() {
int arr1[5] = {1, 3, 5, 7, 9};
int n1 = 5;
int arr2[4] = {2, 4, 6, 8};
int n2 = 4;
int merged[9];
merge(arr1, n1, arr2, n2, merged);
// Print merged array
for (int i = 0; i < n1+n2; i++) {
printf("%d ", merged[i]);
}
return 0;
}
```
In this implementation, the `merge()` function takes two sorted arrays and their lengths as input and combines them into a new sorted array. The function uses three indices `i`, `j`, and `k` to iterate through both arrays and the merged array. It compares the elements at the current indices of both arrays and adds the smaller element to the merged array. When one of the arrays is exhausted, the function adds the remaining elements of the other array to the merged array. The `main()` function initializes two sorted arrays and merges them into a new sorted array. Finally, it prints the merged array.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc