I have an array of the following struct
typedef struct monom {
int coefficient;
int power;
}MONOM;
I have an array of monoms and I want to send it to a merge-sort function, when I do it, using the following call,
mergeSort(&polynomial, logSize);
only the first monom of the array of monoms is sent to the merge-sort function.
When I debug the function I see the full array on the line before the call to mergeSort but when I continue into mergeSort, only the first element is sent.
These are my mergeSort and merge, I'm completely clueless:
void mergeSort(MONOM** polynomial, int size)
{
MONOM** res;
int i;
if (size < 2)
return;
else
{
mergeSort(*polynomial, size/2); // merge first half of array
mergeSort(*polynomial+(size/2),size-(size/2)); // merge second half of array
// allocate result array
res = (MONOM**)malloc(size*sizeof(MONOM*));
// merge both sorted halfs of the array into 'res'
merge(*polynomial,size/2,*polynomial+(size/2),size-(size/2),res);
// copy 'res' to 'arr'
for (i = 0; i < size; i++)
polynomial[i] = res[i];
// release unused memory
free(res);
}
}
void merge(MONOM** poly1, int n1, MONOM** poly2, int n2, MONOM** res)
{
int i1 = 0, i2 = 0;
int resIndex = 0;
while (i1 < n1 && i2 < n2)
{
if (poly1[i1]->power < poly2[i2]->power)
{
res[resIndex] = poly2[i2];
i2++;
}
else if (poly1[i1]->power > poly2[i2]->power)
{
res[resIndex] = poly1[i1];
i1++;
}
else
{
res[resIndex]->power = poly1[i1]->power;
res[resIndex]->coefficient = poly1[i1]->coefficient + poly2[i2]->coefficient;
i1++;
i2++;
}
resIndex++;
}
// fill 'res' array when one of the arrays is finished
while (i1 < n1)
{
res[resIndex] = poly1[i1];
i1++;
resIndex++;
}
while (i2 < n2)
{
res[resIndex] = poly2[i2];
i2++;
resIndex++;
}
}
mergeSort()is of typeMONOM **. You're calling it recursively asmergeSort(*polynomial, size/2)- i. e. as its first argument, you pass in aMONOM *. What do you expect?qsort()from<stdlib.h>works well.