How to search in a row wise increased matrix using C#?

Searching in a row-wise sorted matrix is a common algorithmic problem where each row and column is sorted in ascending order. The naive approach of scanning all elements takes O(M×N) time complexity, but we can optimize this using a smart traversal strategy.

The key insight is to start from either the top-right corner or bottom-left corner of the matrix. From the top-right position, if the target is smaller than the current element, move left; if larger, move down. This approach eliminates either a row or column in each step.

Algorithm

The search algorithm works as follows −

  • Start from the top-right corner of the matrix

  • If the current element equals the target, return true

  • If the target is smaller than the current element, move left (decrement column)

  • If the target is larger than the current element, move down (increment row)

  • Continue until the target is found or boundaries are exceeded

Row-wise Sorted Matrix Search 1 7 10 19 2 8 11 20 3 9 12 21 Start here Searching for: 11 Start at 19 ? Move left to 10 ? Move down to 11 ?

Implementation

Example

using System;

public class MatrixSearcher {
    public bool SearchRowwiseIncrementedMatrix(int[,] mat, int searchElement) {
        int rows = mat.GetLength(0);
        int cols = mat.GetLength(1);
        
        // Start from top-right corner
        int row = 0;
        int col = cols - 1;
        
        while (row < rows && col >= 0) {
            if (mat[row, col] == searchElement) {
                return true;
            }
            else if (searchElement < mat[row, col]) {
                col--; // Move left
            }
            else {
                row++; // Move down
            }
        }
        
        return false;
    }
}

class Program {
    public static void Main() {
        MatrixSearcher searcher = new MatrixSearcher();
        int[,] matrix = {
            { 1,  7, 10, 19 },
            { 2,  8, 11, 20 },
            { 3,  9, 12, 21 }
        };
        
        Console.WriteLine("Matrix:");
        PrintMatrix(matrix);
        
        int target = 11;
        bool found = searcher.SearchRowwiseIncrementedMatrix(matrix, target);
        Console.WriteLine($"Search for {target}: {found}");
        
        target = 15;
        found = searcher.SearchRowwiseIncrementedMatrix(matrix, target);
        Console.WriteLine($"Search for {target}: {found}");
    }
    
    static void PrintMatrix(int[,] matrix) {
        int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                Console.Write($"{matrix[i, j],3} ");
            }
            Console.WriteLine();
        }
    }
}

The output of the above code is −

Matrix:
  1   7  10  19 
  2   8  11  20 
  3   9  12  21 
Search for 11: True
Search for 15: False

Time and Space Complexity

Approach Time Complexity Space Complexity
Linear Search (Brute Force) O(M × N) O(1)
Optimized Search (Top-Right Start) O(M + N) O(1)

Alternative: Bottom-Left Start

Example

using System;

public class AlternativeMatrixSearcher {
    public bool SearchFromBottomLeft(int[,] mat, int searchElement) {
        int rows = mat.GetLength(0);
        int cols = mat.GetLength(1);
        
        // Start from bottom-left corner
        int row = rows - 1;
        int col = 0;
        
        while (row >= 0 && col < cols) {
            if (mat[row, col] == searchElement) {
                return true;
            }
            else if (searchElement > mat[row, col]) {
                col++; // Move right
            }
            else {
                row--; // Move up
            }
        }
        
        return false;
    }
}

class Program {
    public static void Main() {
        AlternativeMatrixSearcher searcher = new AlternativeMatrixSearcher();
        int[,] matrix = {
            { 1,  4,  7, 11 },
            { 2,  5,  8, 12 },
            { 3,  6,  9, 16 }
        };
        
        Console.WriteLine("Searching from bottom-left approach:");
        bool result = searcher.SearchFromBottomLeft(matrix, 5);
        Console.WriteLine($"Found element 5: {result}");
        
        result = searcher.SearchFromBottomLeft(matrix, 13);
        Console.WriteLine($"Found element 13: {result}");
    }
}

The output of the above code is −

Searching from bottom-left approach:
Found element 5: True
Found element 13: False

Conclusion

Searching in a row-wise sorted matrix can be optimized from O(M×N) to O(M+N) by starting from either the top-right or bottom-left corner. This approach eliminates either a row or column in each step, making it significantly more efficient than brute force linear search.

Updated on: 2026-03-17T07:04:36+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements