Java program for Sparse Matrix Representation using Array

This post contain sparse matrix representation in java using array. Before that you may want to learn about the sparse matrix, click the link below.


Java program for Sparse Matrix Representation using Array

public class SparseMatrix  
{ 
  public static void main(String[] args) 
    { 
      // sparse matrix of class 5x6 with 6 non-zero values
        int sparseMatrix[][] 
                = { 
                    {0, 0, 3, 0, 0}, 
                    {0, 0, 4, 0, 8}, 
                    {0, 0, 0, 0, 0}, 
                    {6, 0, 6, 0, 0} 
                }; 
  
  // Looking for non-zero values in the sparse matrix
        int size = 0; 
        for (int i = 0; i < 4; i++){ 
            for (int j = 0; j < 5; j++){ 
                if (sparseMatrix[i][j] != 0){ 
                    size++; 
                } 
            } 
        } 
  
        //result matrix
        int resultMat[][] = new int[3][size]; 
  
        // new matrix 
        int k = 0; 
        for (int i = 0; i < 4; i++){ 
            for (int j = 0; j < 5; j++){ 
                if (sparseMatrix[i][j] != 0)  
                { 
                    resultMat[0][k] = i; 
                    resultMat[1][k] = j; 
                    resultMat[2][k] = sparseMatrix[i][j]; 
                    k++; 
                } 
            } 
        } 
  
        for (int i = 0; i < 3; i++){ 
            for (int j = 0; j < size; j++)
            { 
              System.out.printf("%d ", resultMat[i][j]); 
            } 
            System.out.printf("\n"); 
        } 
    } 
}

Output:

0 1 1 3 3
2 2 4 0 2
3 4 8 6 6