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

Program for Merge Sort in C

Merge Sort: This is a program for merge sort in c
#include"stdio.h"
#include"stdlib.h"
#define MAX 10000
void mergesort(int [],int,int);
//Module for conquer and combine step of merge sort
void merge(int a[],int p,int q,int r){
int k,n1,n2,l[MAX],m[MAX],i,j;
n1=q-p+1;
n2=r-q;
for(i=1;i<=n1;i++)
{
l[i]=a[p+i-1];
}
for(j=1;j<=n2;j++)
m[j]=a[q+j];
l[n1+1]=32000;
m[n2+1]=32000;
i=1;j=1;
for(k=p;k<=r;k++)
{
if(l[i]<=m[j])
{
a[k]=l[i];
i++;
}
else
{
a[k]=m[j];
j++;
}
}
}
//Module for divide step of Merge Sort algo
void mergesort(int a[],int p,int r)
{
int q;
if(p<r)
{
q=(p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
}
int main()
{
int a[MAX],n,i;
printf("Enter total number of elements : "); //elements to sort by merge sort
scanf("%d",&n);
printf("Enter Elements\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
mergesort(a,1,n);
printf("Sorted elements are\n");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
return 1;
}

OUTPUT

Program for merge sort in c
Tags: merge sort in c, merge sort in c/c++ , program for mergesort, c program for mergesort
Also See:   How to Solve Linear Equation in One Variable In C Programming?

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 *