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

2 Answers

0 votes
#include <vector>
#include <iostream>
 
bool isRowSorted(std::vector<std::vector<int>> &matrix, int row) {
    int cols = matrix[0].size();
 
    for (int i = 1; i < cols; i++) {
        if (matrix[row][i - 1] > matrix[row][i]) {
            return false;
        }
    }
 
    return true;
}
 
int main() {
    std::vector<std::vector<int>> matrix =
    {
        std::vector<int> { 4,  7,  9, 12},
        std::vector<int> { 1,  8,  3,  4},
        std::vector<int> {-9, -4, -3,  2},
        std::vector<int> {-8, -3, -9,  4},
        std::vector<int> { 2,  6,  7, 18}
    };
 
    std::cout << "Row 0: " << isRowSorted(matrix, 0) << std::endl;
    std::cout << "Row 1: " << isRowSorted(matrix, 1) << std::endl;
    std::cout << "Row 2: " << isRowSorted(matrix, 2) << std::endl;
    std::cout << "Row 3: " << isRowSorted(matrix, 3) << std::endl;
    std::cout << "Row 4: " << isRowSorted(matrix, 4) << std::endl;
}
 
 
 
  
/*
run:
  
Row 0: 1
Row 1: 0
Row 2: 1
Row 3: 0
Row 4: 1
  
*/

 



answered Jun 22, 2023 by avibootz
edited Jun 23, 2023 by avibootz
0 votes
#include <iostream>
 
#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);

    std::cout << "Row 0: " << isRowSorted(matrix, cols, 0) << std::endl;
    std::cout << "Row 1: " << isRowSorted(matrix, cols, 1) << std::endl;
    std::cout << "Row 2: " << isRowSorted(matrix, cols, 2) << std::endl;
    std::cout << "Row 3: " << isRowSorted(matrix, cols, 3) << std::endl;
    std::cout << "Row 4: " << isRowSorted(matrix, cols, 4) << std::endl;
}
 
 
 
  
/*
run:
  
Row 0: 1
Row 1: 0
Row 2: 0
Row 3: 0
Row 4: 1
 
*/

 



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

Related questions

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