数据结构基础(C语言版)读书笔记002
2.5 稀疏矩阵
稀疏矩阵的定义
下图的矩阵中存在大量零值,这样的矩阵成为稀疏矩阵。
稀疏矩阵的表示
稀疏矩阵的三元组表示:
1 #define MAX_TERMS 101
2
3 typedef struct
4 {
5 int col;
6 int row;
7 int value;
8 } term;
9 term a[MAX_TERMS];
2
3 typedef struct
4 {
5 int col;
6 int row;
7 int value;
8 } term;
9 term a[MAX_TERMS];
稀疏矩阵的转置
矩阵转置就是把矩阵的行列对换。
矩阵转置算法
1)O(cols*elements)
1 void transpose(term a[], term b[])
2 {
3 int n, i, j, currentb;
4 n = a[0].value;
5 b[0].row = a[0].col;
6 b[0].col = a[0].row;
7 b[0].value = n;
8 if (n > 0)
9 {
10 currentb = 1;
11 for (i = 0; i < a[0].col; i++)
12 {
13 for(j = 0; j <= n; j++)
14 {
15 if (a[j].col == i)
16 {
17 b[currentb].row = a[j].col;
18 b[currentb].col = a[j].row;
19 b[currentb].value = a[j].value;
20 currentb++;
21 }
22 }
23 }
24 }
25 }
2 {
3 int n, i, j, currentb;
4 n = a[0].value;
5 b[0].row = a[0].col;
6 b[0].col = a[0].row;
7 b[0].value = n;
8 if (n > 0)
9 {
10 currentb = 1;
11 for (i = 0; i < a[0].col; i++)
12 {
13 for(j = 0; j <= n; j++)
14 {
15 if (a[j].col == i)
16 {
17 b[currentb].row = a[j].col;
18 b[currentb].col = a[j].row;
19 b[currentb].value = a[j].value;
20 currentb++;
21 }
22 }
23 }
24 }
25 }
2) O(cols+elements)
1 void fastTranspose(term a[], term b[])
2 {
3 int rowTerms[MAX_COL], startingPos[MAX_COL];
4 int i, j, numCols = a[0].col, numTerms = a[0].value;
5 b[0].row = numCols; b[0].col = a[0].row;
6 b[0].value = numTerms;
7 if (numTerms > 0)
8 {
9 for (i = 0; i < numCols; i++)
10 {
11 rowTerms[i] = 0;
12 }
13
14 for (i = 1; i <= numTerms; i++)
15 {
16 rowTerms[a[i].col]++;
17 }
18 startingPos[0] = 1;
19
20 for (i = 1; i <= numCols; i++)
21 {
22 startingPos[i] = startingPos[i - 1] + rowTerms[i - 1];
23 }
24
25 for (i = 1; i <= numTerms; i++)
26 {
27 j = startingPos[a[i].col]++;
28 b[j].row = a[i].col;
29 b[j].col = a[i].row;
30 b[j].value = a[i].value;
31 }
32 }
33 }
2 {
3 int rowTerms[MAX_COL], startingPos[MAX_COL];
4 int i, j, numCols = a[0].col, numTerms = a[0].value;
5 b[0].row = numCols; b[0].col = a[0].row;
6 b[0].value = numTerms;
7 if (numTerms > 0)
8 {
9 for (i = 0; i < numCols; i++)
10 {
11 rowTerms[i] = 0;
12 }
13
14 for (i = 1; i <= numTerms; i++)
15 {
16 rowTerms[a[i].col]++;
17 }
18 startingPos[0] = 1;
19
20 for (i = 1; i <= numCols; i++)
21 {
22 startingPos[i] = startingPos[i - 1] + rowTerms[i - 1];
23 }
24
25 for (i = 1; i <= numTerms; i++)
26 {
27 j = startingPos[a[i].col]++;
28 b[j].row = a[i].col;
29 b[j].col = a[i].row;
30 b[j].value = a[i].value;
31 }
32 }
33 }
稀疏矩阵的乘法
参考文献:
posted on 2012-02-19 15:01 jason kung 阅读(376) 评论(0) 编辑 收藏 举报