I have written following mergesort code, but its not working. Could you please help me in error solving. There’s some problem in merge function, as it is priting some address rather than values.
#include<stdio.h>
#include<string.h>
void merge(int *s,int L,int H,int mid)
{
int temp[H-L+1];
int i=L,j=mid+1,k=0;
while((i<=mid)&&(j<=H))
{
if(s[i]<s[j])
{
temp[k] = s[i];
k++;
i++;
}
else
{
temp[k] = s[j];
k++;
j++;
}
}
while(j<=H)
{
temp[k]=s[j];
j++;
k++;
}
while(i<=mid)
{
temp[k] = s[i];
i++;
k++;
}
int x=0;
for(x=0;x<=k-1;x++)
{
s[x+L] = temp[k];
printf("%d\n",s[x+L]);
}
}
void mergesort(int i,int j,int *s)
{
int mid = (i+j)/2;
if(i<j)
{
mergesort(i,mid,s);
mergesort(mid+1,j,s);
merge(s,i,j,mid);
printf("after merging\n");
}
else
{
printf("in the base case\n");
return;
}
}
int main()
{
int str[50];
printf("enter the array\n");
int i,n;
printf("enter n");
scanf("%d",&n);
printf("enter the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&str[i]);
}
for(i=0;i<n;i++)
{
printf("%d",str[i]);
}
mergesort(0,n-1,str);
for(i=0;i<n;i++)
{
printf("%d",str[i]);
}
}
Error in the last loop of merge:
Haven’t looked much harder than that, but it should be a pretty good start. With the code as it was, you’d completely fill your array with rubbish from uninitialised memory.