Merge Sort in C..
//Merge Sort in C..............................
#include<stdio.h>
#include<stdlib.h>
void merge(int *L,int *R,int *A,int nl,int nr)
{
int i=0,j=0,k=0;
while(i<nl && j<nr)
{
if(L[i]<R[j])
{
A[k]=L[i];
i=i+1;
}
else
{
A[k]=R[j];
j=j+1;
}
k=k+1;
}
while(i<nl)
{
A[k]=L[i];
i=i+1;
k=k+1;
}
while(j<nr)
{
A[k]=R[j];
j=j+1;
k=k+1;
}
}
void mergeSort(int *A,int n)
{
int *left,*right;
if(n<2)return;
int mid=n/2;
left = (int*)malloc(mid*sizeof(int));
right = (int*)malloc((n- mid)*sizeof(int));
for(int i=0;i<mid;i++)
{
left[i]=A[i];
}
for(int i=mid;i<n;i++)
{
right[i-mid]=A[i];
}
mergeSort(left,mid);
mergeSort(right,n-mid);
merge(left,right,A,mid,n-mid);
free(left);
free(right);
}
int main()
{
int A[]={2,4,1,6,8,5};
int size= sizeof(A)/sizeof(A[0]);
printf("Before Sorting :\n");
for(int i=0;i<size;i++)
{
printf("%d\n",A[i]);
}
mergeSort(A,size);
int i;
printf("After Sorting :\n");
for(int i=0;i<size;i++)
{
printf("%d\n",A[i]);
}
return 0;
}
No comments