稀疏矩阵的快速转置c语言代码 含int main
时间: 2023-12-21 13:03:19 浏览: 108
稀疏矩阵快速转置C语言算法
以下是包含`main`函数的稀疏矩阵快速转置的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
void sparse_matrix_transpose(int *rows, int *cols, int *vals, int n, int m, int nz)
{
int i, j, k, col_count, *col_counts, *col_starts, *new_rows, *new_cols, *new_vals;
// 统计每一列的非零元素个数
col_counts = (int*)calloc(m, sizeof(int));
for (i = 0; i < nz; i++) {
col_counts[cols[i]]++;
}
// 计算每一列的起始位置
col_starts = (int*)calloc(m + 1, sizeof(int));
col_starts[0] = 0;
for (i = 1; i <= m; i++) {
col_starts[i] = col_starts[i - 1] + col_counts[i - 1];
}
// 创建新的稀疏矩阵
new_rows = (int*)calloc(nz, sizeof(int));
new_cols = (int*)calloc(nz, sizeof(int));
new_vals = (int*)calloc(nz, sizeof(int));
for (i = 0; i < n; i++) {
for (j = rows[i]; j < rows[i + 1]; j++) {
k = col_starts[cols[j]];
new_rows[k] = cols[j];
new_cols[k] = rows[i];
new_vals[k] = vals[j];
col_starts[cols[j]]++;
}
}
// 将新的稀疏矩阵复制回原数组
for (i = 0; i < nz; i++) {
rows[i] = new_rows[i];
cols[i] = new_cols[i];
vals[i] = new_vals[i];
}
// 释放内存
free(col_counts);
free(col_starts);
free(new_rows);
free(new_cols);
free(new_vals);
}
int main()
{
int rows[] = {0, 2, 3, 6, 7, 9};
int cols[] = {2, 3, 0, 1, 3, 1, 2, 0, 2};
int vals[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 5, m = 4, nz = 9;
printf("Original matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = rows[i]; j < rows[i + 1]; j++) {
printf("%d ", vals[j]);
}
printf("\n");
}
sparse_matrix_transpose(rows, cols, vals, n, m, nz);
printf("Transposed matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = rows[i]; j < rows[i + 1]; j++) {
printf("%d ", vals[j]);
}
printf("\n");
}
return 0;
}
```
在`main`函数中,我们定义了一个稀疏矩阵,然后调用`sparse_matrix_transpose`函数对其进行转置,并打印出转置前后的矩阵。
阅读全文