How to check if a given matrix is a sparse matrix (contains a large number of zeros) in Java

1 Answer

0 votes
// A sparse matrix is a matrix in which the majority of elements are zero.

public class Main {

    // Check if a matrix is sparse
    static boolean isSparse(int[][] matrix) {
        int zeroCount = 0;
        int rows = matrix.length;
        int cols = matrix[0].length;
        // Count zeros
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    zeroCount++;
                }
            }
        }

        // A matrix is sparse if more than half of its elements are zero
        return zeroCount > (rows * cols) / 2;
    }

    public static void main(String[] args) {

        int[][] matrix = {
            {2, 0, 5, 0},
            {0, 4, 0, 0},
            {0, 8, 0, 9}
        };

        if (isSparse(matrix)) {
            System.out.println("Matrix is sparse");
        } else {
            System.out.println("Matrix is not sparse");
        }
    }
}


/*
run:

Matrix is sparse

*/

 



answered Nov 19, 2022 by avibootz
edited Apr 23 by avibootz
...