本节目录列表
完整代码:稀疏矩阵.cpp
数据结构代码仓库:DataStruct C++
1. 基础知识(三元组的定义 && 矩阵转置的概念)
1.1 三元组的定义
1.2 矩阵转置的概念
2. 稀疏矩阵转置简单算法
2.1 简单转置算法介绍
2.2 C++代码实现
2.3 简单转置复杂度分析
3.稀疏矩阵转置快速算法
3.1 快速转置算法介绍
3.2 快速转置算法实现效果
3.3 矩阵转置快速算法C++实现
4. 代码实现
4.1 简单转置代码模板实现
template<class ElemType>
void TriSparseMatrix<ElemType>::SimpleTranspose(const TriSparseMatrix<ElemType>& sourse, TriSparseMatrix<ElemType>& dest)
{
dest.rows = sourse.cols;
dest.cols = sourse.rows;
dest.num = sourse.num;
dest.maxSize = sourse.maxSize;
delete[] dest.triElems;
dest.triElems = new Triple<ElemType>[dest.maxSize];
if (dest.num > 0)
{
int destPos = 0;
for (int col = 1; col <= sourse.cols; col++) { // col:1 ~ cols
for (int soursePos = 1; soursePos < sourse.num; soursePos++) { // sourse 的 col
if (sourse.triElems[soursePos].col == col) { // find col
dest.triElems[destPos].row = sourse.triElems[soursePos].col;
dest.triElems[destPos].col = sourse.triElems[soursePos].row;
dest.triElems[destPos].value = sourse.triElems[soursePos].value;
destPos++;
}
}
}
}
}
4.2 快速转置代码模板实现
template<class ElemType>
void TriSparseMatrix<ElemType>::FastTranspose(const TriSparseMatrix<ElemType>& sourse, TriSparseMatrix<ElemType>& dest)
{
dest.rows = sourse.cols;
dest.cols = sourse.rows;
dest.num = sourse.num;
dest.maxSize = sourse.maxSize;
delete[] dest.triElems;
dest.triElems = new Triple<ElemType>[dest.maxSize];
int* cNum = new int(sourse.cols);
int* cPos = new int(sourse.cols);
if (dest.num > 0)
{
for (int col = 1; col <= sourse.cols; col++) cNum[col] = 0; // 初始化cNum
for (int soursePos = 1; soursePos <= sourse.num; soursePos++) { // 得到cNum数组
cNum[sourse.triElems[soursePos].col]++;
}
cPos[1] = 0;
for (int col = 2; col <= sourse.cols; col++) { // 得到cPos数组
cPos[col] = cPos[col - 1] + cNum[col - 1];
}
for (int soursePos = 1; soursePos <= sourse.num; soursePos++) {
int icol = sourse.triElems[soursePos].col;
dest.triElems[cPos[icol]].col = sourse.triElems[soursePos].row;
dest.triElems[cPos[icol]].row = sourse.triElems[soursePos].col;
dest.triElems[cPos[icol]].value = sourse.triElems[soursePos].value;
cPos[icol]++;
}
}
delete[] cNum;
delete[] cPos;
}