重写fastTranspose, 把两个数组 rowTerms和startingPos 合成一个数组。

书上程序:

void fastTranspose(term a[], term b[]){ //书上代码
    //the transpose of a is placed in b
    int rowTerms[MAX_COL], startingPos[MAX_COL];
    int i, j, numCols = a[0].col, numTerms = a[0].value;
    b[0].row = numCols; b[0].col = a[0].row; b[0].value = numTerms;
    if(numTerms > 0){   //非零矩阵
        for(i = 0; i<numCols; i++)
            rowTerms[i] = 0;
        for(i = 1; i <= numTerms; i++)
            rowTerms[a[i].col]++; //计算每行非0值;
        startingPos[0] = 1;
        for(i = 1; i <= numCols; i++)
            startingPos[i] = startingPos[i-1] + rowTerms[i-1];
        for(i = 1; i <= numTerms; i++){
            j = startingPos[a[i].col]++;
            b[j].row = a[i].col;
            b[j].col = a[i].row;
            b[j].value = a[i].value;
        }
    }
    
}

更改后 将两个数组合并成一个,SPR[],前半是每行的非0元个数,后半是每行的起始position

void fastTranspose(term a[], term b[]){
    // the transpose of a is placed in b
    int SPR[MAX_COL * 2];
    int i, j, numCols = a[0].col, numTerms = a[0].value;
    b[0].row = numCols; b[0].col = a[0].row; b[0].value = numTerms;
    if(numTerms > 0){   //非零矩阵
        for(i = 0; i<numCols; i++)
            SPR[i] = 0;
        for(i = 1; i <= numTerms; i++)
            SPR[a[i].col]++; //计算每行非0值;
        SPR[a[0].value] = 1;
        for(i = a[0].value; i <= a[0].value + numCols; i++)
            SPR[i] = SPR[i-1] + SPR[i-1-a[0].value];
        for(i = 1; i <= numTerms; i++){
            j = SPR[a[i].col + a[0].value]++;
            b[j].row = a[i].col;
            b[j].col = a[i].row;
            b[j].value = a[i].value;
        }
    }
    
}


猜你喜欢

转载自blog.csdn.net/sinat_22014829/article/details/46502713