How to merge two sorted arrays in C Language

/*Merging two sorted arrays:
input: two sorted arrays a and b and 1 output array c
1.compare a and b, if a[i]< c[k] put that in c[k] else put b[j]in c[k]
2.when any of array is empty put the remaining elements of other array's
elements in C as it is.*/
#include<stdio.h>
#include<stdlib.h>
void mergeSorted(int a[], int b[], int c[], int asize, int bsize, int
csize);

int main()
{
int i;
int a[]={5,10,15,20,25};
int b[]={2,4,6,8,10};
int c[10];
mergeSorted(a,b,c,5,5,10);
printf("Merged Array is:\n");
for(i=0;i<10;i++)
{
printf("%d ",c[i]);/* 2 4 5 6 8 10 10 15 20 25 */
}

printf("\n\n");
return 0;
}

void mergeSorted(int *a, int *b, int *c, int asize, int bsize, int csize)
{
printf("\nin mergeSorted:\n");
int ai=0,bi=0,ci=0,i;
//csize=asize+bsize;
/*compare a[ai]<b[bi] till any of the array ends.*/
while((ai<asize) && (bi<bsize))
{
if(a[ai]<=b[bi])
{
c[ci]=a[ai];
ci++;
ai++;
}
else
{
c[ci]=b[bi];
ci++;
bi++;
}
}
if(ai>=asize)
for(i=ci;i<csize;i++,bi++)
c[i]=b[bi];

else if(bi>=bsize)
for(i=ci;i<csize;i++,ai++)
c[i]=a[ai];


}

No comments:

Post a Comment