一、头文件
二、结构体
三、初始化
四、转置过程
五、测试函数
六、主函数
七、运行结果
一、头文件
#include <stdio.h>
#include <malloc.h>
二、结构体
typedef struct Triple
{
int i;
int j;
int e;
}Triple,*TriplePtr;
typedef struct CompressedMatrix
{
int rows,columns,numElements;
Triple *elements;
}CompressedMatrix,*CompressedMatrixPtr;
三、初始化
//初始化
CompressedMatrixPtr initCompressedMatrix(int newRows,int newColumns,int newElements,int**data)
{
int i;
CompressedMatrixPtr resultPtr = (CompressedMatrixPtr)malloc(sizeof(struct CompressedMatrix));
resultPtr->rows = newRows;
resultPtr->columns = newColumns;
resultPtr->numElements = newElements;
resultPtr->elements = (TriplePtr) malloc(newElements*sizeof(struct Triple));
for(i = 0;i<newElements;i++)
{
resultPtr->elements[i].i = data[i][0];
resultPtr->elements[i].j = data[i][1];
resultPtr->elements[i].e = data[i][2];
}
return resultPtr;
}
四、转置过程
CompressedMatrixPtr transposeCompressedMatrix(CompressedMatrixPtr newPtr)
{
//申请空间
int i,tempColumn,tempPosition;
int * tempColumnCounts = (int*)malloc(newPtr->columns *sizeof(int));
int *tempOffsets = (int*)malloc(newPtr->columns*sizeof(int));
for(i = 0;i<newPtr->columns ;i++)
{
tempColumnCounts[i] = 0;
}
CompressedMatrixPtr resultPtr = (CompressedMatrixPtr)malloc(sizeof(struct CompressedMatrix));
resultPtr->rows = newPtr->columns ;
resultPtr->columns = newPtr->rows ;
resultPtr->numElements = newPtr->numElements ;
resultPtr->elements = (TriplePtr)malloc(newPtr->numElements *sizeof(struct Triple));
for(i = 0;i<newPtr->numElements ;i++)
{
tempColumnCounts[newPtr->elements [i].j]++;
}
tempOffsets[0] = 0;
for(i = 1;i<newPtr->columns ;i++)
{
tempOffsets[i] = tempOffsets[i-1]+tempColumnCounts[i-1];
printf("tempOffsets[%d] = %d\r\n",i,tempOffsets[i]);
}
for(i=0;i<newPtr->numElements ;i++)
{
tempColumn = newPtr->elements [i].j;
tempPosition = tempOffsets[tempColumn];
resultPtr->elements [tempPosition].i = newPtr->elements [i].j;
resultPtr->elements [tempPosition].j = newPtr->elements [i].i;
resultPtr->elements [tempPosition].e = newPtr->elements [i].e;
tempOffsets[tempColumn]++;
return resultPtr;
}
}
五、测试函数
void compressedMatrixTest(){
CompressedMatrixPtr tempPtr1, tempPtr2;
int i, j, tempElements;
tempElements = 4;
int** tempMatrix1 = (int**)malloc(tempElements * sizeof(int*));
for(i = 0; i < tempElements; i ++){
tempMatrix1[i] = (int*)malloc(3 * sizeof(int));
}
int tempMatrix2[4][3] = {{0, 0, 2}, {0, 2, 3}, {2, 0, 5}, {2, 1, 6}};
for(i = 0; i < tempElements; i ++){
for(j = 0; j < 3; j ++) {
tempMatrix1[i][j] = tempMatrix2[i][j];
}
}
tempPtr1 = initCompressedMatrix(2, 3, 4, tempMatrix1);
printf("After initialization.\r\n");
printCompressedMatrix(tempPtr1);
tempPtr2 = transposeCompressedMatrix(tempPtr1);
printf("After transpose.\r\n");
printCompressedMatrix(tempPtr2);
}
六、主函数
int main(){
compressedMatrixTest();
return 1;
}
七、运行结果