Algorithm of Merge Sort
| Step 1: | I = 0 J = 0 K = 0 |
| Step 2: | Repeat Step3 while I <= N1 – 1 and J <= N2 – 1 |
| Step 3: | If List1 [I] < List2 [J] then List3[K] = List1 [I] I = I + 1 K= K + 1 Else List3 [K] = List2 [J] J = J + 1 K = K + 1 |
| Step 4: | Repeat Step5 while I <= N1-1 |
| Step 5: | List3[K] = List1 [I] I = I + 1 K= K + 1 |
| Step 6: | Repeat Step7 while J <= N2-1 |
| Step 7: | List3[K] = List2[J] J = J + 1 K= K + 1 |
Program of Merge Sort
#include<stdio.h>
#include<conio.h>
#define N1 5
#define N2 3
void main()
{
void Merge(int *a,int *b,int *c);
int a[N1],i,b[N2],c[N1+N2];
clrscr();
printf("Enter sort Elements in List1\n");
for(i=0;i<N1;i++)
{
printf("Enter Value of A[%d]:",i);
scanf("%d",&a[i]);
}
printf("Enter sort Elements in List2\n");
for(i=0;i<N2;i++)
{
printf("Enter Value of A[%d]:",i);
scanf("%d",&b[i]);
}
Merge(a,b,c);
printf("Sorted List\n");
for(i=0;i<N1+N2;i++)
{
printf("c[%d]=%d\n",i,c[i]);
}
getch();
}
void Merge(int *a,int *b,int *c)
{
int i=0,j=0,k=0;
while(i<=N1-1 && j<=N2-1)
{
if(a[i]<b[j])
{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=b[j];
j++;
k++;
}
}
while(i<=N1-1)
{
c[k]=a[i];
i++;
k++;
}
while(j<=N2-1)
{
c[k]=b[j];
j++;
k++;
}
}