Program to Count all Sorted Rows in Matrix
Definition & Explanation
Example:
Input:
Output:
More Description
Program Logic
Desc
C
Method 1 :
#include <stdio.h>
int isSortedRow(int row[], int cols) {
for (int i = 0; i < cols - 1; i++) {
if (row[i] > row[i + 1])
return 0;
}
return 1;
}
int countSortedRows(int matrix[][3], int rows, int cols) {
int count = 0;
for (int i = 0; i < rows; i++) {
if (isSortedRow(matrix[i], cols))
count++;
}
return count;
}
int main() {
int matrix[3][3] = {
{1, 2, 3},
{2, 3, 4},
{3, 2, 1}
};
int rows = 3, cols = 3;
int sorted_rows_count = countSortedRows(matrix, rows, cols);
printf("Number of sorted rows: %d\n", sorted_rows_count); // Output: 2 (first two rows are sorted)
return 0;
}
Output :
C++
Method 1 :
#include <iostream>
using namespace std;
bool isSortedRow(int row[], int cols) {
for (int i = 0; i < cols - 1; i++) {
if (row[i] > row[i + 1])
return false;
}
return true;
}
int countSortedRows(int matrix[][3], int rows, int cols) {
int count = 0;
for (int i = 0; i < rows; i++) {
if (isSortedRow(matrix[i], cols))
count++;
}
return count;
}
int main() {
int matrix[3][3] = {
{1, 2, 3},
{2, 3, 4},
{3, 2, 1}
};
int rows = 3, cols = 3;
int sorted_rows_count = countSortedRows(matrix, rows, cols);
cout << "Number of sorted rows: " << sorted_rows_count << endl; // Output: 2 (first two rows are sorted)
return 0;
}
Output :
JAVA
Method 1 :
public class Main {
public static boolean isSortedRow(int[] row) {
for (int i = 0; i < row.length - 1; i++) {
if (row[i] > row[i + 1])
return false;
}
return true;
}
public static int countSortedRows(int[][] matrix) {
int count = 0;
for (int[] row : matrix) {
if (isSortedRow(row))
count++;
}
return count;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{2, 3, 4},
{3, 2, 1}
};
int sortedRowsCount = countSortedRows(matrix);
System.out.println("Number of sorted rows: " + sortedRowsCount); // Output: 2 (first two rows are sorted)
}
}
Output :
Python
Method 1 :
def is_sorted_row(row):
# Check if the row is sorted in non-decreasing order
for i in range(len(row) - 1):
if row[i] > row[i + 1]:
return False
return True
def count_sorted_rows(matrix):
count = 0
for row in matrix:
if is_sorted_row(row):
count += 1
return count
# Example usage:
matrix = [
[1, 2, 3],
[2, 3, 4],
[3, 2, 1]
]
sorted_rows_count = count_sorted_rows(matrix)
print("Number of sorted rows:", sorted_rows_count) # Output: 2 (first two rows are sorted)