Problem: Merge Sort
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void merge(int a[],int left,int mid, int right)
{
int i,j,k;
int n1=mid-left+1;
int n2=right-mid;
int *L,*R;
L=(int *)malloc(n1*sizeof(int));
R=(int *)malloc(n2*sizeof(int));
for(i=0;i<n1;i++)
{
L[i]=a[left+i];
}
for(j=0;j<n2;j++)
{
R[j]=a[mid+1+j];
}
i=0;
j=0;
k=left;
while(i<n1 && j<n2)
{
if(L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
a[k]=L[i];
i++;
k++;
}
while(j<n2)
{
a[k]=R[j];
j++;
k++;
}
}
void mergesort(int a[],int left, int right)
{
if(left<right)
{
int mid=(left+right)/2;
mergesort(a,left,mid);
mergesort(a,mid+1,right);
merge(a,left,mid,right);
}
}
void main()
{
int *a,i,size;
clrscr();
printf("ENTER THE SIZE OF ARRAY:");
scanf("%d",&size);
a=(int *)malloc(size*sizeof(int));
printf("\nENTER %d VALUES IN ARRAY: ",size);
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
mergesort(a,0,size-1);
printf("Array after sorting:");
for(i=0;i<size;i++)
{
printf("%d\t",a[i]);
}
getch();
}
Comments