稀疏矩阵的转置运算(三元组顺序表)
三元组顺序表
1 #define MAXSIZE 1000//稀疏矩阵非零元素个数 2 typedef int ElementType;//稀疏矩阵元素类型 3 4 typedef struct 5 { 6 int row; 7 int col; 8 ElementType value; 9 }Triple; 10 11 typedef struct 12 { 13 int rows; 14 int cols; 15 int nums;//非零元素个数 16 Triple data[MAXSIZE]; 17 }TSMatrix;//Triple Sequence Matrix
按列序递增_1
1 void TransposeSMatrix_1(TSMatrix A, TSMatrix* B) 2 { 3 int i; 4 int j; 5 int k; 6 B->rows = A.cols; 7 B->cols = A.rows; 8 B->nums = A.nums; 9 10 if (B->nums > 0) 11 { 12 j = 0; 13 for (k = 1; k <= A.cols; k++) 14 {//按列序递增 15 for (i = 0; i <= A.nums; i++) 16 {//遍历所有非零元素,找到对应下标 17 if (A.data[i].col == k) 18 { 19 B->data[j].row = A.data[i].col; 20 B->data[j].col = A.data[i].row; 21 B->data[j].value = A.data[i].value; 22 j++; 23 } 24 } 25 } 26 } 27 }
按列序递增_2(非零元素所在列全部排序完成直接结束)
1 void TransposeSMatrix_2(TSMatrix A, TSMatrix* B) 2 { 3 int i; 4 int j; 5 int k; 6 B->rows = A.cols; 7 B->cols = A.rows; 8 B->nums = A.nums; 9 10 if (B->nums > 0) 11 { 12 j = 0; 13 for (k = 1; k <= A.cols; k++) 14 {//按列序递增 15 for (i = 0; i <= A.nums; i++) 16 {//遍历所有非零元素,找到对应下标 17 if (A.data[i].col == k) 18 { 19 B->data[j].row = A.data[i].col; 20 B->data[j].col = A.data[i].row; 21 B->data[j].value = A.data[i].value; 22 j++; 23 if (j == A.nums) 24 {//非零元素所在的列全部排序完成 25 return; 26 } 27 } 28 } 29 } 30 } 31 }
按列序递增_3(每次在非零元素中寻找列值最小的元素)
1 void TransposeSMatrix_3(TSMatrix A, TSMatrix* B) 2 { 3 int i; 4 int j; 5 int min; 6 B->rows = A.cols; 7 B->cols = A.rows; 8 B->nums = A.nums; 9 10 for (i = 0; i < A.nums; i++) 11 { 12 min = 0; 13 for (j = 1; j < A.nums; j++) 14 {//记录最小列值的下标 15 if (A.data[j].col < A.data[min].col) 16 { 17 min = j; 18 } 19 } 20 B->data[i].row = A.data[min].col; 21 B->data[i].col = A.data[min].row; 22 B->data[i].value = A.data[min].value; 23 A.data[min].col = A.cols + 1;//考察完的列值标记为最大列值+1,即下次不再考虑 24 } 25 }
一次定位快速转置算法
1 void FastTransposeSMatrix(SMatrix A, SMatrix* B)//一次定位快速转置 2 { 3 int i; 4 int j; 5 int num[MAXSIZE] = { 0 };//每列非零元素个数 6 int position[MAXSIZE] = { 0 };//转置前非零元素某列 对应的 转置后的矩阵非零数组中某行的 起始位置 7 B->rows = A.cols; 8 B->cols = A.rows; 9 B->nums = A.nums; 10 11 for (i = 0; i < A.nums; i++) 12 {// num数组下标就是转置后的行号; num 数组元素代表转置后该行有几个非零元素 13 num[A.data[i].col]++; 14 } 15 16 position[1] = 1; 17 for (i = 2; i < A.cols; i++) 18 {//本行元素在非零矩阵数组中起始位置 = 前一行非零元素起始位置 + 前一行非零元素个数 19 position[i] = position[i - 1] + num[i - 1]; 20 } 21 22 for (i = 0; i < A.nums; i++) 23 { 24 j = position[A.data[i].col];//通过查表 position 数组来找转置对应位置 25 B->data[j].row = A.data[i].col; 26 B->data[j].col = A.data[i].row; 27 B->data[j].value = A.data[i].value; 28 position[A.data[i].col]++;//修改 position[A.data[i].col] ,将其指向该行下一个元素的存储位置 29 } 30 }

浙公网安备 33010602011771号