Merge Sort (Recursive) > C Program
Analysis of Algorithm
Merge Sort (Recursive) > C Program
#include<stdio.h>#include<conio.h>
void merge(int x[],int lb1,int ub1,int ub2)
{
int temp[50],i,j,k;
i=lb1;
j=ub1+1;
k=0;
while(i<=ub1 && j<=ub2)
if(x[i]<x[j])
temp[k++]=x[i++];
else
temp[k++]=x[j++];
while(i<=ub1)
temp[k++]=x[i++];
while(j<=ub2)
temp[k++]=x[j++];
for(i=lb1,j=0;i<=ub2;i++,j++)
x[i]=temp[j];
}
void mergesort(int x[],int lb,int ub)
{
int mid;
if(lb<ub)
{
mid=(lb+ub)/2;
mergesort(x,lb,mid);
mergesort(x,mid+1,ub);
merge(x,lb,mid,ub);
}
}
void main()
{
clrscr();
int A[100],n,i;
printf("Enter the number of elements in the array:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element %d",i+1);
scanf("%d",&A[i]);
}
mergesort(A,0,n-1);
printf("The sorted array is :\n");
for(i=0;i<n;i++)
printf("%d ",A[i]);
getch();
}
Comments
Post a Comment