A sparse matrix is a matrix that contains many zero entries. The following shows an example: \(\begin{bmatrix}15&0&0&22&0\\0&11&3&0&0\\0&0&0&-6&0\\0&0&0&0&0\\91&0&0&0&0\\0&0&28&0&0\end{bmatrix}\)
In the above example, only 7 of 30 elements are nonzero. Storing them in a two-dimensional array wastes memory space. Therefore we use the following representation to store a sparse matrix in an unsorted array of triples, <row, column, value>:
#define MAX_TERMS 1001
int num_row, num_column;
struct Term { int row; int column; int value; } M[MAX_TERMS];
And the above example is stored in the array M as: num_row = 6, num_column = 5;M[0]=<5,2,28>、[1]=<0,0,15>、[2]=<4,0,91>、[3]=<0,3,22>、[4]=<1,1,11>、[5]=<1,2,3>、[6]=<2,3,−6>、[7]=<0,0,0>。The final entry A[7], which contains a zero value, represents the end of the array.
(a) (5 分) Please write the pseudo code of the transpose(Term A[], Term B[]) function that transposes a sparse matrix A[] into another sparse matrix B[]. For example, <4,0,91> in the above example will be converted to <0,4,91> in B[].
(b) (5 分) What is the time complexity for finding the value of an element in row \(i\) and column \(j\), from a sparse matrix with \(N_R\) rows and \(N_C\) columns that contains just \(N\) nonzero elements? Please explain your answer briefly.
(c) (10 分) Please suggest a different representation of sparse matrix, such that finding the value of an element in row \(i\) and column \(j\) from a sparse matrix may be finished in \(O(1)\) constant time complexity in average cases. Please also explain your answer.
(a) 轉置:每個 <row, col, val> 變成 <col, row, val>,行列數對調。為了讓 B 依新的 row(也就是 A 的 column)排好,先數每個 column 有幾項,算出每個 column 在 B 的起始位置
transpose(Term A[], Term B[]):
n = 0
while A[n].value != 0: n++ // 非零項個數(A[n] 是結尾標記)
B.num_row = A.num_column; B.num_column = A.num_row
for c = 0 .. A.num_column-1: count[c] = 0
for k = 0 .. n-1: count[ A[k].column ]++ // 每個 column 有幾項
start[0] = 0
for c = 1 .. A.num_column-1: start[c] = start[c-1] + count[c-1]
for k = 0 .. n-1:
p = start[ A[k].column ]++ // 這一項在 B 的位置
B[p].row = A[k].column
B[p].column = A[k].row
B[p].value = A[k].value
B[n].row = B[n].column = B[n].value = 0 // 結尾標記
時間 \(O(N+N_C)\),額外空間 \(O(N_C)\)
簡單版:對 \(c=0..N_C-1\) 各掃一遍 A,凡 column=c 的就依序放進 B,時間 \(O(N_C\cdot N)\);上面是用 counting 省掉重複掃描
(b) 三元組沒有排序,要找 \((i,j)\) 只能從頭掃,每項比對 row、column 是否等於 \((i,j)\);找不到(值為 0)要掃完全部 \(N\) 項
\(O(N)\)(與 \(N_R,N_C\) 無關)
若三元組依 \((row,column)\) 排序,可用 binary search,\(O(\log N)\)
(c) 用 hash table:以 \((i,j)\) 為 key(例如 \(key=i\cdot N_C+j\))、只存非零項;hash function 設計得均勻、table 大小與 \(N\) 同量級(load factor 為常數)
查 \((i,j)\):算 \(h(key)\),到該 bucket 找 key;找到就回傳 value,沒有就回傳 0
平均每個 bucket 只有常數個項目,所以平均 \(O(1)\);空間 \(O(N)\)。最壞(全部撞同一格)\(O(N)\)
hash table(key=\((i,j)\)):平均 \(O(1)\) 查值