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

1 Answer

0 votes
using System;

public class Program
{
	private static bool isRowSorted(int[,] matrix, int row) {
        int cols = matrix.GetLength(1);

		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 = { { 1,   2,   3,   4,  0},
                          {-5,  -4,   0,   8,  9},
                          { 2, 100,   8, 100,  3},
                          { 1,   7, 100,   9,  6},
                          { 9,  10,  11,  12, 13} };
                           
		Console.WriteLine("Row 0: " + isRowSorted(matrix, 0));
		Console.WriteLine("Row 1: " + isRowSorted(matrix, 1));
		Console.WriteLine("Row 2: " + isRowSorted(matrix, 2));
		Console.WriteLine("Row 3: " + isRowSorted(matrix, 3));
		Console.WriteLine("Row 4: " + isRowSorted(matrix, 4));
	}
}




/*
run:
 
Row 0: False
Row 1: True
Row 2: False
Row 3: False
Row 4: True
 
*/

 



answered Jun 23, 2023 by avibootz

Related questions

1 answer 128 views
2 answers 166 views
2 answers 168 views
1 answer 131 views
1 answer 147 views
...