C PROGRAM TO MERGE TWO SORTED ARRAY - Computer Programming

# Computer Programming

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

## Sunday, January 29, 2012

ALGORITHM TO MERGE TWO SORTED ARRAY

ENTER (a[10],n)
1.  Repeat step 2 for i = 0 to (n-1)
2.  Input a[i]
3.  Return

DISPLAY(c[20],p)
1.  Repeat step 2 for k = 0 to p-1
2.  Print c[k]
3.  Return

MAIN( )
1.  Start
2.  Input no. of elements in 1st & 2nd array as ‘n’ & ‘m’
3.  Enter (a.n)
4.  Enter (b,m)
5.  i = j = k = 0
6.  Repeat step 7 to 12 while ((i < n)&&(j < m))
7.  If (a[i] >= b[j]),goto step 9
8.  c[k+1] = a[i+1]
9.  If a[i] = b[j] ,goto step 11
10. c[k++] = b[j++]
goto step 7
11. c[k++] = a[i++]
12. j++
13. Repeat step 14 while (i<n)
14. c[k++] = a[i++]
15. Repeat step 16 while m > j
16. c[k++] = b[j++]
17. Display merged arrays as display(c;k)
18. Exit

#include<stdio.h>
#include<conio.h>
void main( )
int n,m,i,j,k,c[40],a[20],b[20];
clrscr ();
printf("Enter limit for A:");
scanf("%d",&n);
printf  ("\nEnter limit for B:");

scanf("%d",&m);
printf("Enter elements for A:-\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter elements for B:-\n");
for(j=0;j<m;j++)
scanf("%d",&b[j]);
i=j=k=0;
while(i<n&&j<m)
{
if(a[i]<b[j])
c[k++]=a[i++];
else
if(a[i]>b[j])
c[k++]=b[j++];
else

{
c[k++]=b[j++];
i++;

j++;
}
}

if(i<n)
{
int t;
for(t=0;t<n;t++)

c[k++]=a[i++];
}
if(j<m)
{
int t;
for(t=0;t<m;t++)
{
c[k++]=b[j++];
}
}
printf("\n");
for(k=0;k<(m+n);k++)
printf("\t \n %d ",c[k]);
getch();