#include <stdio.h>

void mergeArrays(int arr1[], int size1, int arr2[], int size2, int merged[]) {
    int i, j;

    // Copy elements of the first array
    for (i = 0; i < size1; i++) {
        merged[i] = arr1[i];
    }

    // Copy elements of the second array
    for (j = 0; j < size2; j++) {
        merged[i + j] = arr2[j];
    }
}

int main() {
    int array1[] = {1, 3, 5, 7};
    int array2[] = {2, 4, 6, 8};
    int size1 = sizeof(array1) / sizeof(array1[0]);
    int size2 = sizeof(array2) / sizeof(array2[0]);
    int merged[size1 + size2];

    mergeArrays(array1, size1, array2, size2, merged);

    // Print the merged array
    printf("Merged Array: ");
    for (int k = 0; k < size1 + size2; k++) {
        printf("%d ", merged[k]);
    }
    printf("\n");

    return 0;
}

Explanation

  1. Include Headers: The program begins with the inclusion of the standard input-output header (<stdio.h>).
  2. Function Definition: The mergeArrays function takes two arrays along with their sizes and a third array to store the merged result.
  3. Copying Elements:
    • The first for loop copies elements from the first array (arr1) to the merged array.
    • The second for loop continues copying elements from the second array (arr2) to the merged array, starting from the index after the last element copied from arr1.
  4. Main Function:
    • Two example arrays, array1 and array2, are defined, along with their sizes.
    • A merged array is created to hold the combined elements.
    • The mergeArrays function is called to perform the merging.
  5. Print Result: Finally, the merged array is printed to the console.

Output

For the input arrays {1, 3, 5, 7} and {2, 4, 6, 8}, the output will be:

javascriptCopy codeMerged Array: 1 3 5 7 2 4 6 8 

This program effectively merges two arrays into one, achieving O(n + m) time complexity, where n and m are the sizes of the two input arrays.

4o mini

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights