Best Way To Check If It Is A Sparse Matrix Java Program

Do you know best way to check if it is a sparse matrix java program? No!!! Then continue reading…

what is sparse matrix?

Sparse matrix also known as a sparse array is a two dimensional array. In this matrix majority of elements are zero and very few are non zero elements.

Why we are using sparse matrix?

Because sparse matrix reduces the scanning time and how exactly it reduces the scanning time is if there is m X n matrix where m = 50 and n is also n = 50.

This means, to find where exactly value exists or scanning all the elements you require 2500 iterations.

So instead of scanning 2500 times you can use a sparse matrix. In sparse matrix you can directly get the values that exists in the matrix.

There are two ways to represent sparse matrix,

  1. three column form
  2. linked list

 

example: Best Way To Check If It Is A Sparse Matrix Java Program

Also Read – Matrix Multiplication In Java

import java.util.Scanner;

public class Sparse_Matrix {

public static void main(String[] args) {
 
Scanner sc = new Scanner(System.in);
System.out.println("Please enter dimensions of matrix: ");
 
int x = sc.nextInt();
int y = sc.nextInt();
double given_Matrix[][] = new double[x][y];
 
int check_Zero = 0;
System.out.println("Please enter elements of matrix: ");
 
for(int a = 0;a < x;a++)
{
for(int b = 0;b < y;b++)
{
given_Matrix[a][b] = sc.nextDouble();
if(given_Matrix[a][b] == 0)
{
check_Zero++;
}
}
}
 
if(check_Zero > (x * y) / 2)
{
System.out.println("It is a sparse matrix!!!");
}
else
{
System.out.println("Sorry!! It is not a sparse matrix.");
}
 
sc.close();

}

}

Output:

Best Way To Check If It Is A Sparse Matrix Java Program

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *