Hello again,
This is one of my favourite forums in the net.
And now for the question:
I am trying the recursive mergeSort approach, but now I'm using an array
of pointers, in which each of them will point to values in another array, and in a sorted way.
And now for the problem... In order to free the pointers array, I need to free each one of the pointers, and then free the int** address.
But by doing so, it calls a runtime error:
"Debug assertion failed". I think that one means that I didn't handle the pointers in the right way. After searching for several hours, I'm lost. I can't find bugs in my code. It prints output perfectly and saves the original array intact. But it has a problem by freeing the pointers in the array.
These are my functions... I mean these functions are the only ones in my code that deals with handling and updating the pointers. Now, can someone tell me what's wrong here?
If you need all of the code, just ask for it, but if there's a problem, it must be in here...
Hold on tight for this one...
Code:
int** pointerSort(int* arr, int size){
int** outA;
int i;
outA=(int**)malloc(size*sizeof(int*));
if (outA!=NULL)
{
for (i=0; i<size; i++)
outA[i]=&arr[i];
mergeSort(outA,size);
}
else
return NULL;
return outA;
}
void mergeSort(int** arr, int size)
{
int** res;
int numRes;
if (size==1)
{
return;
}
else
{
mergeSort(arr, size/2);
mergeSort(arr+size/2, size-size/2);
res=(int**)malloc(size*sizeof(int*));
if (res!=NULL)
{
merge(arr, size/2, arr+size/2, size-size/2, res, &numRes);
copyPtrsArray(arr, res, size);
free((void*)res);
}
else
{
printf("\n failure in sorting \n");
return;
}
}
}
void merge(int** src1, int size1, int** src2, int size2, int** res, int* numRes)
{
int i=0,j=0, iRes=0;
while ((i<size1)&&(j<size2))
{
if (*src1[i]<*src2[j])
{
res[iRes]=src1[i];
iRes++;
i++;
}
else
{
res[iRes]=src2[j];
iRes++;
j++;
}
}
while (j<size2)
{
res[iRes]=src2[j];
iRes++;
j++;
}
while (i<size1)
{
res[iRes]=src1[i];
iRes++;
i++;
}
*numRes=size2+size1;
}
void freeArray(int** a1, int size){
int i;
for (i=0; i<size; i++)
free((void*)a1[i]);
free((void*)a1);
}