将数组发送到函数只会发送数组的第一个元素

时间:2013-07-18 17:27:33

标签: c arrays sorting struct mergesort

我有一个以下结构的数组

typedef struct monom {
    int coefficient; 
    int power;
}MONOM;

我有一个monom数组,我想将它发送到合并排序函数,当我这样做时,使用以下调用,

mergeSort(&polynomial, logSize);

只有monom数组的第一个monom被发送到merge-sort函数。

当我调试函数时,我在调用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++;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个,

  

mergeSort(polynomial,logSize); (给定多项式是MONOM *或MONOM []类型)

  

void mergeSort(MONOM * polynomial,int size)