I need to implement 2 types of storing sparse matrix in C++:
- Linked List
- Array (effective way)
Space complexity is very important here. What are the most effective ways to do it?
I need to implement 2 types of storing sparse matrix in C++:
Space complexity is very important here. What are the most effective ways to do it?
On
Since the matrix is sparse, you only need to store the cells that are filled in. A simple lookup of coordinate to value should do. Ideally you should use something with fast lookup like a map O(log n) or a unordered_map O(1).
On
An efficient way would be to use hash map (for each row) of hash maps (to store elements in each row by column index). Then would be able to access any element in O(1) time.
You can implement all numeric algorithms, like addition and multiplication iterating only through non-zero elements which will give you better complexity then O(N * M) where N and M are number of columns and rows in a matrix.
nnz: non-zero number of sparse matrixrow_size: matrix row numbercolumn_size: matrix column numberThere are many ways, their space complexity :
2*nnz + row_sizenumber of memory2*nnz + column_sizenumber of memory3*nnznumber of memoryFor space complexity :
If
row_size > column_size, useCSCformat, otherwise, useCSRformat.For Time complexity:
For
CSRformat, Row will be indexed byO(1)time, Column will be indexed byO(log(k))time, by binary search the Column,kis the number of non-zero element of that row. So value will be indexed byO(log(k))time.For
COOformat, value will be indexed inO(1)time.Format details
[1] https://en.wikipedia.org/wiki/Sparse_matrix
[2] https://software.intel.com/en-us/node/471374