Merging two arrays involves combining the elements of both arrays into a single array in a sorted order.
Example:
#include <stdio.h>
#define MAX_SIZE 100
// Function to merge two sorted arrays
void mergeArrays(int arr1[], int size1, int arr2[], int size2, int mergedArr[]) {
int i = 0, j = 0, k = 0;
// Compare elements from both arrays and merge them into the merged array
while (i < size1 && j < size2) {
if (arr1[i] < arr2[j]) {
mergedArr[k++] = arr1[i++];
} else {
mergedArr[k++] = arr2[j++];
}
}
// Copy the remaining elements from arr1, if any
while (i < size1) {
mergedArr[k++] = arr1[i++];
}
// Copy the remaining elements from arr2, if any
while (j < size2) {
mergedArr[k++] = arr2[j++];
}
}
int main() {
int arr1[MAX_SIZE] = {1, 3, 5, 7, 9}; // First sorted array
int size1 = 5;
int arr2[MAX_SIZE] = {2, 4, 6, 8, 10}; // Second sorted array
int size2 = 5;
int mergedArr[MAX_SIZE * 2]; // Merged array (double the size of input arrays)
// Call the mergeArrays function to merge the two arrays
mergeArrays(arr1, size1, arr2, size2, mergedArr);
// Print the merged array
printf(“Merged Array:\n”);
for (int i = 0; i < size1 + size2; i++) {
printf(“%d “, mergedArr[i]);
}
printf(“\n”);
return 0;
}
Explanation:
- We have a function
mergeArraysthat takes two sorted arrays (arr1andarr2), their sizes (size1andsize2), and an arraymergedArrwhere the merged result will be stored. - Inside
mergeArrays, we use three indicesi,j, andkto traversearr1,arr2, andmergedArrrespectively. - We compare elements from both
arr1andarr2and merge them intomergedArrin sorted order. - After one of the arrays is fully processed, we copy the remaining elements from the other array to
mergedArr. - n the
mainfunction, we define two sorted arrays (arr1andarr2) and their sizes (size1andsize2). - We also define an array
mergedArrto store the merged result. - We call the
mergeArraysfunction to mergearr1andarr2intomergedArr. - Finally, we print the merged array
mergedArr.