How to find the number of sorted rows in a matrix with Java

1 Answer

0 votes
public class MyClass {
    private static boolean isRowSorted(int[][] matrix, int row) {
        int cols = matrix[0].length;
          
        for (int i = 1; i < cols; i++) {
            if (matrix[row][i - 1] > matrix[row][i])  {
                return false;
            }
        }
  
        return true;
    }
  
    public static void main(String args[]) {
        int matrix[][] = { { 4,  7,  9, 12},
                           { 1,  8,  3,  4},
                           {-9, -4, -3,  2},
                           {-8, -3, -9,  4},
                           { 2,  6,  7, 18} };
 
        int rows = matrix.length;
        int count = 0;
         
        for (int i = 0; i < rows; i++) {
            if (isRowSorted(matrix, i)) {
                count++;
            }
        }
         
        System.out.println("Total sorted rows: " + count);
    }
}
  
  
  
  
/*
run:
  
Total sorted rows: 3
  
*/

 



answered Jun 23, 2023 by avibootz
edited Jun 23, 2023 by avibootz
...