c-program-to-merge-two-arrays
admin
#c-program--merge-two-arrays
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.
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.
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]
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();
}
Merged array is: 2 2 5 10 15 20 35 60 65 90 100 112
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.Comparison Loop:
x
and y
.z
.Remaining Elements:
z
.Output:
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.