C Program for Merge Sort Arrange a List of Integers in Ascending order

Estudies4you
1 #include<stdio.h>
2 void Merge_Sort(int a[],int n);
3 void mpass(int a[],int low,int high);
4 void msort(int a[],int low,int mid,int high);
5 int main()
6 {
7 int a[10];
8 int i,j,temp,n,key;
9 printf("Enter the no.of elements : ");
10 scanf("%d",&n);
11 for(i=0;i<n;i++)
12 {
13 printf("Enter a[%d] element : ",i);
14 scanf("%d",&a[i]);
15 }
16 printf("Before Sorting array elements are : ");
17 for(i=0;i<n;i++)
18 {
19 printf("%d ",a[i]);
20 }
21 Merge_Sort(a,n);
22 printf("\nafter Sorting array elements are : ");
23 for(i=0;i<n;i++)
24 {
25 printf("%d ",a[i]);
26 }
27 }
28 void Merge_Sort(int a[],int n)
29 {
30 mpass(a,0,n-1);
31 }
32 void mpass(int a[],int low,int high)
33 {
34 int mid;
35 if(low<high)
36 {
mid=(low+high)/2;
mpass(a,low,mid);
mpass(a,mid+1,high);
msort(a,low,mid,high);
}
}
void msort(int a[],int low,int mid,int high)
{
int n,i,j,k;
int b[20];
n=low;
i=low;
j=mid+1;
while(i<=mid&&j<=high)
{
if(a[i]<=a[j])
{
b[n]=a[i];
i++;
}
else
{
b[n]=a[j];
j++;
}
n++;
}
if(i>mid)
{
for(k=j;k<=high;k++)
{
b[n]=a[k];
n++;
}
}
else
{
for(k=i;k<=mid;k++)
{
b[n]=a[k];
n++;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}
OUTPUT:
Enter the no.of elements : 5
Enter a[0] element : 8
Enter a[1] element : 4
Enter a[2] element : 6
Enter a[3] element : 2
Enter a[4] element : 3
Before Sorting array elements are : 8 4 6 2 3
after Sorting array elements are : 2 3 4 6 8
To Top