In this instructional exercise, you will get the program for merge sort in C.
Merge sort runs in O (n log n) running time. It is effective arranging calculation with close to
ideal number of correlation. Recursive calculation utilized for merge sort goes under the classification of gap and vanquish procedure.
A variety of n components is part around its middle delivering two littler clusters.
After these two clusters are arranged freely, they can be merged to create the last arranged exhibit.
The way toward parting and blending can be conveyed recursively until there is just a single component in the exhibit.
An exhibit with 1 component is constantly arranged.
An example of merge sort in C is given underneath. First isolate the rundown into the littlest unit (1 component),
at that point contrast every component and the nearby rundown to sort and merge the two adjoining records.
At long last, every one of the components is arranged and merged.
Program for Merge Sort in C
#include<stdio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
Output
On the off chance that you have any questions with respect to the above
program for merge sort in C at that point remark underneath.