Write c program to sort the elements from an array using merge sort

Merge Sort

#include<stdio.h>
#include<conio.h>
int n;

//To define functions
mergesort(int a[],int lb,int ub);
merge(int a[],int lb,int mid,int ub);

int main()
{
int a[10];
int i,j,temp,k;
clrscr();
printf("\nEnter how many number: ");
scanf("%d",&n);
for(i=0;i<n;i++)
   {
   printf("\nEnter elements:");
scanf("%d",&a[i]);
   }
mergesort(a,0,n-1);
printf("\nSorted array is:");
for(i=0;i<n;i++)
printf(" %d",a[i]);
getch();
return 0;

}

//To sort the elements
mergesort(int a[],int lb,int ub)
{
int mid;
int k;
if(lb<ub)
{
mid=(lb+ub)/2;
mergesort(a,lb,mid);
mergesort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
merge(int a[],int lb,int mid,int ub)
{
int i,j,k;
int temp[20];
for(i=lb;i<=ub;i++)
temp[i]=a[i];
i=lb;
j=mid+1;
k=lb;
while(i<=mid&&j<=ub)
{
if(temp[i]<temp[j])
{
a[k]=temp[i];
i++;
  k++;
}
else
{
a[k]=temp[j];
j++;
k++;
}
}
while(i<=mid)
{
a[k]=temp[i];
i++;
k++;
}
while(j<=ub)
{
a[k]=temp[j];
j++;
k++;
}
return 0;
}

0 Comments