← Back to all posts
Merge sort

Hello,
Actually I am learning DS a subject in my semester and have doubt in the following code of the merge sort, though by dry run I am not able to find any error, I am not getting why my array is not getting sorted.
I hope someone can help me with this.
The code is in given below.
Regards
Yuvraj.

``````#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);
k++;
i++;
}
else
{
*(A+k)=*(r+j);
k++;
j++;
}
}
while(i<nl)
{   printf("%d =##\n",*(l+i));
*(A+k)=*(l+i);
i++;
k++;
}
while(j<nr)
{   printf("%d =**\n",*(r+j));
*(A+k)=*(r+j);
j++;
k++;
}
}
void mergesort(int *A,int n)
{
if(n<2)
return;
int mid=n/2;
int *left=malloc(sizeof(int)*(n-mid));
int *right=malloc(sizeof(int)*(mid));
int i;

for(i=0;i<(n-mid);i++)
*(left+i)=*(A+i);
for(i=(n-mid);i<n;i++)
*(right+i)=*(A+i);

mergesort(left,(n-mid));
mergesort(right,mid);
merge(left,right,A,(n-mid),mid);
}

void disp(int *arr,int n)
{   int i=0;
for(i=0;i<n;i++)
printf("%d ",*(arr+i));
printf("\n");
}
int main()
{
int i,n,*A;
printf("Please enter the no. of elements\n");
scanf("%d",&n);
A=(int *)(malloc(sizeof(int)*n));
printf("Please enter the elements of the array\n");
for(i=0;i<n;i++)
scanf("%d",A+i);
printf("The array is \n");
disp(A,n);
mergesort(A,n);
printf("The sorted array is \n");
disp(A,n);
return 0;
}``````