How to check if a given row is sorted 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} };
 
        System.out.println("Row 0: " + isRowSorted(matrix, 0));
        System.out.println("Row 1: " + isRowSorted(matrix, 1));
        System.out.println("Row 2: " + isRowSorted(matrix, 2));
        System.out.println("Row 3: " + isRowSorted(matrix, 3));
        System.out.println("Row 4: " + isRowSorted(matrix, 4));
    }
}
 
 
 
 
/*
run:
 
Row 0: true
Row 1: false
Row 2: true
Row 3: false
Row 4: true
 
*/

 



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

Related questions

1 answer 207 views
2 answers 272 views
2 answers 286 views
1 answer 206 views
1 answer 210 views
...