Program to merge two sorted array in C
Let L1{1,3,5,6}
L2={2,4,7}
After merge
Result{1,2,3,4,5,6,7}
Code that use to merge
while(i<=l1&&j<=l2)
{
if(a[i]<b[j])
{
res[k]=a[i];
k++;
i++;
}
else
{
res[k]=b[j];
k++;
j++;
}
}
while(i<=l1)
{
res[k]=a[i];
k++;
i++;
}
while(j<=l2)
{
res[k]=b[j];
k++;
j++;
}
C code to merge two sorted array
#include<stdio.h>
#include<string.h>
void merge(int a[],int b[],int l1,int l2);
void main()
{
int a[4]={1,3,5,6};
int b[3]={2,4,7};
merge(a,b,4,3);
}
void merge(int a[],int b[],int l1,int l2)
{
int i=0;
int j=0;
int k=0;
int r=l1+l2;
int res[10];
while(i<=l1&&j<=l2)
{
if(a[i]<b[j])
{
res[k]=a[i];
k++;
i++;
}
else
{
res[k]=b[j];
k++;
j++;
}
}
while(i<=l1)
{
res[k]=a[i];
k++;
i++;
}
while(j<=l2)
{
res[k]=b[j];
k++;
j++;
}
for(i=0;i<r;i++)
{
printf("%d",res[i]);
}
}
0 Comments