# implement merge sort

merge sort program in c  is a type of sorting program,  merge sort is a one of the sorting Technic. in this method of sorting  each and every elements are divide and merge, in that time all the elements are sorted either ascending order or descending order. merge sort program is given below, you can also download executable “.C” file in the below link.

mergesort program in c

Program:

#include<stdio.h>
void mergesort(int a[],int low,int high);
void merging(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[50],n,i;
printf(“Enter the no of elementn”);

scanf(“%d”,&n);
printf(“Enter array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
mergesort(a,0,n-1);
printf(“n sorted array is:”);
for(i=0;i<n;i++)
printf(“%dt”,a[i]);
return 0;
}

void mergesort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merging(a,low,mid,mid+1,high);
}
}

void merging(int a[],int i1,int j1,int i2,int j2)
{
int temp[50];
int i,j,k;
i=i1; //first list
j=i2; //second list
k=0;

while(i<=j1 && j<=j2)  // elements in both list
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}

while(i<=j1)  // copy remaining element
temp[k++]=a[i++];

while(j<=j2)
temp[k++]=a[j++];

for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j]; // copy element from temp[] to a[]}

Output: