Topic-34:Merging operation in Array

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 mergeArrays that takes two sorted arrays (arr1 and arr2), their sizes (size1 and size2), and an array mergedArr where the merged result will be stored.
    • Inside mergeArrays, we use three indices i, j, and k to traverse arr1, arr2, and mergedArr respectively.
    • We compare elements from both arr1 and arr2 and merge them into mergedArr in sorted order.
    • After one of the arrays is fully processed, we copy the remaining elements from the other array to mergedArr.
    • n the main function, we define two sorted arrays (arr1 and arr2) and their sizes (size1 and size2).
    • We also define an array mergedArr to store the merged result.
    • We call the mergeArrays function to merge arr1 and arr2 into mergedArr.
    • Finally, we print the merged array mergedArr.

    Leave a Comment

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