Program for Merge Sort is given below:
//Merge sort Program
#include<stdio.h>
void merge(int A[],int lb,int mid,int ub)
{
int i,j,k,B[50];
i=lb;
j=mid+1;
k=lb;
while(i<=mid && j<=ub)
{
if(A[i]<=A[j])
{
B[k] = A[i];
i++;
k++;
}
else
{
B[k]=A[j];
j++;
k++;
}
}
if(i>mid)
{
while(j<=ub)
{
B[k]=A[j];
j++;
k++;
}
}
else
{
while(i<=mid)
{
B[k]=A[i];
i++;
k++;
}
}
for(k=lb;k<=ub;k++)
{
A[k]=B[k];
}
}
void mergesort(int A[],int lb,int ub)
{
if(lb<ub)
{
int mid=(lb+ub)/2;
mergesort(A,lb,mid);
mergesort(A,mid+1,ub);
merge(A,lb,mid,ub);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int n,A[50];
printf("Enter the size of the array :");
scanf(" %d",&n);
printf("Enter the array :\n");
for(int i=0;i<n;i++)
{
scanf(" %d",&A[i]);
}
printf("the unsorted array is :\n");
printArray(A,n);
mergesort(A,0,n-1);
printf("the sorted array is :\n");
printArray(A,n);
return 0;
}
Output
Enter the size of the array :9
Enter the array :
15 5 24 8 1 3 16 10 20
the unsorted array is :
15 5 24 8 1 3 16 10 20
the sorted array is :
1 3 5 8 10 15 16 20 24