我有以下结构的数组
typedef struct monom {
int coefficient;
int power;
}MONOM;
我有一个单体数组,我想将它发送到一个合并排序函数,当我这样做时,使用以下调用,
mergeSort(&polynomial, logSize);
只有单声道数组的第一个单声道被发送到合并排序函数。
当我调试函数时,我在调用 mergeSort 之前在行上看到了完整的数组,但是当我继续进入 mergeSort 时,只发送了第一个元素。
这些是我的mergeSort和merge,我完全一无所知:
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++;
}
}