sparse matric (DSA)
#include<stdio.h>
typedef struct matrix
{
int row;
int col;
int val;
}matrix;
void cpynz(int row, int col, int matrices[50][50], matrix sparseA[100])
{
int i, j, k = 1; // nzelem = 0;
sparseA[0].row = row;
sparseA[0].col = col;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (matrices[i][j] != 0)
{
sparseA[k].row = i+1;
sparseA[k].col = j+1;
sparseA[k].val = matrices[i][j];
k++;
}
}
}
sparseA[0].val = k - 1;
}
void transpose(int totalrows , int totalcols , matrix sparseA[50] , matrix transp[50])
{
transp[0].row = sparseA[0].col;
transp[0].col = sparseA[0].row;
transp[0].val = sparseA[0].val;
int count=sparseA[0].val;
int i;
int rowterm[50];
int startingindex[50];
for (i = 0; i < sparseA[0].col; i++)
{
rowterm[i] = 0;
}
int colno;
for ( i = 1; i <=count; i++)
{
colno = sparseA[i].col;
rowterm[colno]++;
}
startingindex[0] = 1;
for ( i = 1; i < sparseA[0].col; i++)
{
startingindex[i] = startingindex[i-1] + rowterm[i-1];
}
for ( i = 1; i <=count; i++)
{
colno = sparseA[i].col;
int n = startingindex[colno];
transp[n].row = sparseA[i].col;
transp[n].col = sparseA[i].row;
transp[n].val = sparseA[i].val;
startingindex[colno]++;
}
}
void display( matrix transp[50])
{
int i;
printf("row col val\n");
for (i = 0; i <= transp[0].val; i++)
{
printf("%d%5d%5d\n", transp[i].row, transp[i].col, transp[i].val);
}
}
int main(){
int totalrows;
int totalcols;
int matrices[50][50];
matrix sparseA[50] , transp[50];
printf("Enter the total rows of the matrix : ");
scanf("%d", &totalrows);
printf("Enter the total columns of the matrix : ");
scanf("%d",&totalcols);
int i,j;
for (i = 0; i < totalrows; i++)
{
for (j = 0; j < totalcols; j++)
{
printf("enter the element at (%d , %d) position = ", i+1, j+1 );
scanf("%d", &matrices[i][j]);
}
}
cpynz(totalrows , totalcols , matrices, sparseA);
transpose(totalrows, totalcols, sparseA, transp);
display(transp);
return 0;
}