How to check if a given row is sorted in a matrix with C

1 Answer

0 votes
#include <stdio.h>  
#include <stdbool.h>  

#define COLS 5

bool isRowSorted(int matrix[][COLS], int cols, int row) {
    for (int i = 1; i < cols; i++) {
        if (matrix[row][i - 1] > matrix[row][i]) {
            return false;
        }
    }

    return true;
}

int main() {
    int matrix[][COLS] = { { 1,   2,   3,   4,  5 },
                           { 5,   6, 100,   8,  1 },
                           { 2, 200,   8, 400,  3 },
                           { 1,   7, 300,   9,  6 },
                           { 9,  10,  11,  12, 13 } };

    int cols = sizeof matrix[0] / sizeof(int);

    printf("Row 0: %d\n", isRowSorted(matrix, cols, 0));
    printf("Row 1: %d\n", isRowSorted(matrix, cols, 1));
    printf("Row 2: %d\n", isRowSorted(matrix, cols, 2));
    printf("Row 3: %d\n", isRowSorted(matrix, cols, 3));
    printf("Row 4: %d\n", isRowSorted(matrix, cols, 4));
}




/*
run:

Row 0: 1
Row 1: 0
Row 2: 0
Row 3: 0
Row 4: 1

*/

 



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

Related questions

2 answers 119 views
1 answer 119 views
2 answers 148 views
2 answers 151 views
1 answer 118 views
...