Question

#include<stdio.h>
#include<conio.h>
//#include<alloc.h>

int* mergeSort(int*,int);
int* merge(int*,int*,int);

void main()
{
  int n;int i=0;
  int *a,*b;

  scanf("%d",&n);
  a=(int)malloc(n*sizeof(int));
  for(;i<n;i++)
     scanf("%d",&a[i]);

  b=mergeSort(a,n);
  for(i=0;i<n;i++)
     printf("%d ",b[i]);

}

int* mergeSort(int *b,int n)
{
  int temp,*s;

  if(n>2)
  {
     mergeSort(b,n/2);
     mergeSort(b+n/2,n-n/2);
     s=merge(b,b+n/2,n);

     return s;
  }
  else if(n==2)
  {
     if(b[0]>b[1])
     {
         temp=b[0];
         b[0]=b[1];
         b[1]=temp; 
     }
     return;
  }
}

int* merge(int* a,int* c,int n)
{
  int i=0,j=0,k=0,
  int* x;

  while( (j ! =n/2) && (k != (n-n/2)) && (i < n))
  {
       if(a[j]<c[k])
       {
             x[i]=a[j];
             j++; 
             i++;
       }
       else
       {
             x[i]=c[k];
             k++;
             i++;
       }
   }
   for( ; j<n/2; j++,i++)
      x[i]=a[j];

   for( ; k < (n-n/2); k++,i++)
      x[i]=c[k];

   return x;
}

when i run this code,it hangs after inputting all the elements of the array in first for loop. Please help me, how can i correct it to make it work successfully? it hangs on calling the mergeSort function from main() function.

Was it helpful?

Solution

it hangs after inputting all the elements of the array in first for loop.

hangs? Are you sure... that's pretty good considering your merge code declares a pointer to an int:

int *x;

and never initializes it, then tries to jump to an offset (i) past it:

x[i]=a[j];

Change your code to this:

int *x = malloc(n * sizeof(int));

and it should stop crashing/hanging whatever.

FYI, whenever you malloc() you should free() right now you have memory leaks.

OTHER TIPS

There are some things wrong, not only basic things like void main instead of int main but also eg the return; in mergeSort() which should return int* and the uninitialized x. Also one important thing about the algorithm: You seem to assume that n is a power of 2: you recursively divide by 2 and assume that it always is an untruncated integer.

For starters, the code doesn't compile in a C++ compiler (I know it's C code, but still...),

a couple of problems are:

line 11:

a=(int)malloc(n*sizeof(int));

why are you casting a pointer to an int? a is an int *

line 38:

return;

you are returning from mergeSort without a return value...that can't be good

I recommend that you fix all the compiler errors and warnings, then try again

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top