Write a ‘C’ program to sort an array elements using Merge Sort technique.
#include<stdio.h>
#include<conio.h>
int n;
void display(int a[])
{
int i;
printf("\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
void merge(int a[],int low,int mid,int high)
{
int i,j,k,b[20];
i=low;
j=mid+1;
k=0;
while ((i<=mid) && (j<=high))
{
if (a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while (i<=mid)
b[k++]=a[i++];
while (j<=high)
b[k++]=a[j++];
//copy merged element from b to a
for(j=low,k=0;j<=high;j++,k++)
a[j]=b[k];
}
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);
merge(a,low,mid,high);
}
}
void main()
{
int a[20],i;
clrscr();
printf("\nHow many numbers: ");
scanf("%d",&n);
printf("\nEnetr the unsorted numbers: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
display(a);
getch();
}
#include<stdio.h>
#include<conio.h>
int n;
void display(int a[])
{
int i;
printf("\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
void merge(int a[],int low,int mid,int high)
{
int i,j,k,b[20];
i=low;
j=mid+1;
k=0;
while ((i<=mid) && (j<=high))
{
if (a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while (i<=mid)
b[k++]=a[i++];
while (j<=high)
b[k++]=a[j++];
//copy merged element from b to a
for(j=low,k=0;j<=high;j++,k++)
a[j]=b[k];
}
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);
merge(a,low,mid,high);
}
}
void main()
{
int a[20],i;
clrscr();
printf("\nHow many numbers: ");
scanf("%d",&n);
printf("\nEnetr the unsorted numbers: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
display(a);
getch();
}