How to write a C Program Merge Sort in C Programming Language ?
In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.See More : Merge sort
C program for merge sorting :
Solution For C Program ://MERGE SORT
/* c program for merge sorting.*/
/*Write a c program to merge two sorted arrays*/
#include<stdio.h>
main()
{
int a[10],m,n,b[10],p;
static int i;
clrscr();
printf("enter the size of the first array\n");
scanf("%d",&m);
printf("enter the elements into thae array\n");
for(i=0;i<m;i++)
scanf("%d",&a[i]);
printf("enter the size of the second array\n");
scanf("%d",&n);
printf("enter the elements into the array\n");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
merge_sort(a,b,m,n);
getch();
}
merge_sort(int a[],int b[],int m,int n)
{
int c[25],p;
static int i,j,k;
i=0;
j=0;
while(i<m && j<n)
{
if(a[i]<b[j])
{
c[k]=a[i];
k++;
i++;
}
else if(a[i]>b[j])
{
c[k]=b[j];
k++;
j++;
}
else
{
c[k]=a[i];
i++;
k++;
}
}
if(i<m)
{
for(p=i;p<m;p++)
{
c[k]=a[i];
k++;
i++;
}
}
else if(j<n)
{
for(p=j;p<n;p++)
{
c[k]=b[j];
k++;
j++;
}
}
printf("after sorting the elements are\n");
for(i=0;i<k;i++)
printf("%d ",c[i]);
}