Mergesort implementation in C
Mergesort based on divide and conquer technique.
so first divide the array element recursively
void mergesort(int a[],int lb,int ub)
{
int mid;
if(lb!=ub)
{
mid=(lb+ub)/2;
mergesort(a,lb,mid);
mergesort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
Then merge list sorted list
void merge(int a[],int lb,int mid,int ub)
{
int i,j,k;
i=lb;
j=mid+1;
k=lb;
int b[10];
while(i<=mid&&j<=ub)
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(j<=ub)
{
b[k++]=a[j++];
}
while(i<=mid)
{
b[k++]=a[i++];
}
for(i=lb;i<=ub;i++)
{
a[i]=b[i];
}
}
#include<stdio.h>
void mergesort(int a[],int lb,int ub);
void merge(int a[],int lb,int mid,int ub);
void main()
{
int a[10];
int n;
int i;
int lb,ub;
printf("enter number of element");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
lb=0;
ub=n-1;
mergesort(a,lb,ub);
printf("after sorting");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}
void mergesort(int a[],int lb,int ub)
{
int mid;
if(lb!=ub)
{
mid=(lb+ub)/2;
mergesort(a,lb,mid);
mergesort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
void merge(int a[],int lb,int mid,int ub)
{
int i,j,k;
i=lb;
j=mid+1;
k=lb;
int b[10];
while(i<=mid&&j<=ub)
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(j<=ub)
{
b[k++]=a[j++];
}
while(i<=mid)
{
b[k++]=a[i++];
}
for(i=lb;i<=ub;i++)
{
a[i]=b[i];
}
}
Output
enter number of element5
1
23
4
6
56
after sorting1
4
6
23
56
0 Comments