How to search for a number in a sorted matrix in C#

1 Answer

0 votes
using System;

class MatrixSearch
{
    public static bool SearchMatrix(int[,] matrix, int target) {
        int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);

        int row = 0;
        int col = cols - 1;

        while (row < rows && col >= 0) {
            int value = matrix[row, col];
            if (value == target) {
                Console.WriteLine($"Found: i = {row} j = {col}");
                return true;
            }
            else if (value > target) {
                col--;
            }
            else {
                row++;
            }
        }

        Console.WriteLine("Not found");
        return false;
    }

    static void Main()
    {
        int[,] matrix = {
            {2, 3, 5, 7, 8},
            {10, 13, 17, 18, 19},
            {25, 26, 30, 37, 38},
            {43, 46, 50, 51, 99}
        };

        SearchMatrix(matrix, 37);
    }
}



/*
run:

Found: i = 2 j = 3

*/

 



answered Oct 7, 2025 by avibootz

Related questions

...