c-program-to-merge-two-arrays

admin

1/19/2025

  #c-program--merge-two-arrays

Go Back
Start learningc-program--merge-two-arrays

C Program to Merge Two Arrays: Data Structure Tutorial

Introduction

Merging two sorted arrays is a fundamental operation in data structures and programming. This operation combines two pre-sorted arrays into a single sorted array, making it easier to process and retrieve elements efficiently. In this tutorial, we'll explore how to merge two arrays in C with a step-by-step explanation and code implementation.


What is a List in Data Structures?

A list is an abstract data type that stores elements in an ordered manner. This structure facilitates efficient insertion, deletion, and retrieval of elements. By merging two sorted arrays into one, you create a unified list that retains the order and properties of a sorted structure.


How to Merge Two Sorted Arrays

The merging process involves comparing elements from two arrays and appending the smaller element to a new array. This process continues until all elements from both arrays are added to the new array. Below is an example:

First Array: [2, 5, 10, 100, 112]
Second Array: [2, 15, 20, 35, 60, 65, 90]

Steps for Linear Merge:

  1. Start with two sorted arrays.
  2. Compare the first element of each array.
  3. Append the smaller element to the target array.
  4. Move the pointer of the array whose element was smaller.
  5. Repeat until all elements from both arrays are processed.

C Code for Merging Two Arrays

Here's the C program to merge two sorted arrays into a single sorted array:

#include<stdio.h>
#include<conio.h>

void main() {
  int x[5] = {2, 5, 10, 100, 112};
  int y[7] = {2, 15, 20, 35, 60, 65, 90};
  int z[12], i = 0, j = 0, k = 0;
  clrscr();

  while (i < 5 && j < 7) {
    if (x[i] < y[j])
      z[k++] = x[i++];
    else
      z[k++] = y[j++];
  }

  while (i < 5) {
    z[k++] = x[i++];
  }

  while (j < 7) {
    z[k++] = y[j++];
  }

  printf("\nMerged array is:");
  for (k = 0; k < 12; k++)
    printf(" %d", z[k]);

  getch();
}

Output:

Merged array is: 2 2 5 10 15 20 35 60 65 90 100 112

Explanation of the Code

  1. Initialization:

    • x and y are the two sorted arrays.
    • z is the target array where merged elements are stored.
    • i, j, and k are index pointers for x, y, and z respectively.
  2. Comparison Loop:

    • Compare elements from x and y.
    • Append the smaller element to z.
    • Increment the pointer of the respective array.
  3. Remaining Elements:

    • If one array is fully processed, append the remaining elements from the other array directly to z.
  4. Output:

    • Display the merged array.

Conclusion

Merging two arrays in C programming involves iterating through the elements of both arrays, comparing them, and appending the smaller element to the target array. The provided code illustrates a straightforward implementation of this process.