博客中代码都经过运行并且没有bug
//三元组的转置算法
class Program
{
//矩阵的非零元素的表示
struct Triple
{
public int i, j;//该非零元素位于矩阵的行号和列号
public int element;//该非零元素的值
}
//矩阵的表示
struct TriMatrix
{
public Triple[] data;//存储三元组表示的矩阵的非零元素
public int mu, nu, tu;//mu表示矩阵的行数,nu表示矩阵的列数,tu表示矩阵的非零元素的个数
}
//初始化一个矩阵
static TriMatrix InitTriMatrix()
{
TriMatrix s = new TriMatrix();
s.mu = 5;
s.nu = 5;
s.tu = 5;
s.data = new Triple[s.tu];
Triple tempTriple = new Triple();
tempTriple.i = 0;
tempTriple.j = 0;
tempTriple.element = 1;
s.data[0] = tempTriple;
tempTriple = new Triple();
tempTriple.i = 0;
tempTriple.j = 3;
tempTriple.element = 3;
s.data[1] = tempTriple;
tempTriple = new Triple();
tempTriple.i = 1;
tempTriple.j = 4;
tempTriple.element = 2;
s.data[2] = tempTriple;
tempTriple = new Triple();
tempTriple.i = 3;
tempTriple.j = 1;
tempTriple.element = 1;
s.data[3] = tempTriple;
tempTriple = new Triple();
tempTriple.i = 4;
tempTriple.j = 0;
tempTriple.element = 2;
s.data[4] = tempTriple;
return s;
}
static TriMatrix TransposeTriMatrix(TriMatrix s)
{
TriMatrix t = new TriMatrix();
t.mu = s.nu;
t.nu = s.mu;
t.tu = s.tu;
t.data = new Triple[t.tu];
//存储转置后的矩阵t每一行的非零元素的个数
int[] array = new int[s.nu];
for (int i = 0; i < s.tu; i++)
{
int j = s.data[i].j;
array[j]++;
}
//存储转置后的矩阵t每一行的前面的非零元素的总个数
int[] cpot = new int[s.nu];
cpot[0] = 0;
for (int i = 1; i < array.Length; i++)
{
cpot[i] = cpot[i - 1] + array[i - 1];
}
//正式进行转置操作
for (int i = 0; i < s.tu; i++)
{
int j = s.data[i].j;
int index = cpot[j];
t.data[index].i = s.data[i].j;
t.data[index].j = s.data[i].i;
t.data[index].element = s.data[i].element;
cpot[j]++;
}
return t;
}
static void Main(string[] args)
{
TriMatrix s = InitTriMatrix();
TriMatrix t = TransposeTriMatrix(s);
int sIndex = 0;
for (int i = 0; i < s.mu; i++)
{
for (int j = 0; j < s.nu; j++)
{
if (sIndex<s.tu && s.data[sIndex].i == i && s.data[sIndex].j == j)
{
Console.Write(s.data[sIndex].element + " ");
sIndex++;
}
else
{
Console.Write("0 ");
}
}
Console.WriteLine();
}
Console.WriteLine();
int tIndex = 0;
for (int i = 0; i < t.mu; i++)
{
for (int j = 0; j < t.nu; j++)
{
if (tIndex < t.tu && t.data[tIndex].i == i && t.data[tIndex].j == j)
{
Console.Write(t.data[tIndex].element + " ");
tIndex++;
}
else
{
Console.Write("0 ");
}
}
Console.WriteLine();
}
Console.ReadKey();
}
}