Monday , December 18 2017
Home / C / Program for Merge Sort in C

Program for Merge Sort in C

#include<stdio.h>
#include<conio.h>
void mergesort(int [],int,int);
void merge(int [],int,int,int);
void main()
{
int ar[30],p,n,r,i;
clrscr();
printf("\n enter the size of array \n");
scanf("%d",&n);
printf("\n enter the values of array \n");
for(i=1;i<=n;i++)
{

scanf("%d",&ar[i]);
}
p=1;
r=n;
mergesort(ar,p,r);
printf("AFTER SORTING \n");
for(i=1;i<=r;i++)
{
printf("%d \n",ar[i]);
}
getch();
}
void mergesort(int ar[],int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
mergesort(ar,p,q);
mergesort(ar,q+1,r);
merge(ar,p,q,r);
}
}
void merge(int ar[30],int p,int q,int r)
{
int i,j,k,n1,n2;
int lar[30],rar[30];
n1=q-p+1;
n2=r-q;
for(i=1;i<=n1;i++)

lar[i]=ar[p+i-1];
for(j=1;j<=n2;j++)
rar[j]=ar[q+j];
lar[n1+1]=32000;
rar[n2+1]=32000;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(lar[i]<=rar[j])
{
ar[k]=lar[i];
i++;
}
else
{
ar[k]=rar[j];
j++;
}
}
}

 

Also See:   c program to check for twin prime numbers

Check Also

How to Solve Linear Equation in One Variable In C Programming?

C Program to Solve any Linear Equation in One Variable Find complete C program to ...

Leave a Reply

Your email address will not be published. Required fields are marked *