Merge Sort |Merge sort in C language|
Program to Merge two sorted array to a single sorted array
code:
#include <stdio.h>
void main()
{
int array1[50], array2[50], array3[100], m, n, i, j, k = 0;
printf("\n Enter size of array Array 1: ");
scanf("%d", &m);
printf("\n Enter sorted elements of array 1: \n");
for (i = 0; i < m; i++)
{
scanf("%d", &array1[i]);
}
printf("\n Enter size of array 2: ");
scanf("%d", &n);
printf("\n Enter sorted elements of array 2: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &array2[i]);
}
i = 0;
j = 0;
while (i < m && j < n)
{
if (array1[i] < array2[j])
{
array3[k] = array1[i];
i++;
}
else
{
array3[k] = array2[j];
j++;
}
k++;
}
if (i >= m)
{
while (j < n)
{
array3[k] = array2[j];
j++;
k++;
}
}
if (j >= n)
{
while (i < m)
{
array3[k] = array1[i];
i++;
k++;
}
}
printf("\n After merging: \n");
for (i = 0; i < m + n; i++)
{
printf("\n%d", array3[i]);
}
}
Time Complexity : O(n1 + n2)
Auxiliary Space : O(n1 + n2)
In this program we can see that two sorted arrays are given by the user and it gets compared with on another like polynomial addition and it gets stored in the third array in sorted order.
Output:
-
Here the first array size is 4 with 4 sorted elements
and the second array size is 3 where 3 sorted elements
are stored and every element from both the array are compared and
they get stored in the 3rd array in sorted order itself it works like polynomial addition
(Polynomial Addition (ayyavuu.blogspot.com)
(Polynomial Addition (ayyavuu.blogspot.com)
So,useful.Please keep Updating.👍
ReplyDelete