mercredi 26 décembre 2018

Segmentation Fault for Merge function of Merge Sort

My task is to implement just the merge function of merge sort algorithm.My idea is to create an auxilliary array to store the sorted values.I have mainted 2 pointers,one for left sorted array and other for right sorted array.

I am having difficulty in figuring out why am I getting segmentation fault?

void merge(int arr[], int l, int m, int r)
{

 int temp[r-l+1];int count=0;
 int *ptr1=(int*) malloc(sizeof(int));
 int * ptr2=(int*) malloc(sizeof(int));
 ptr1=&arr[l];
 ptr2=&arr[m+1];
 while(ptr1!=(&arr[m+1]) && ptr2!=NULL)
 {
     if(*ptr1>=*ptr2)
     {
      temp[++count]=*ptr2;
      ptr2++;
     }
     else 
     {
         temp[++count]=*ptr1;
         ptr1++;
     }
 }
 if(ptr1==&arr[m+1])
 {
     while(ptr2)
     {
        temp[++count]=*ptr2;
        ptr2++;
     }
 }
 if(ptr2==NULL)
 {
  while(ptr1!=&arr[m+1])
     {
        temp[++count]=*ptr1;
        ptr1++;
     }   
 }
 for(int i=0;i<r-l+1;i++)
 {
     arr[i]=temp[i];
 }
}

Input: 2

5

4 1 3 9 7

10

10 9 8 7 6 5 4 3 2 1

Expected Output:

1 3 4 7 9

1 2 3 4 5 6 7 8 9 10

My Output:Segmentation fault

Aucun commentaire:

Enregistrer un commentaire