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

A row-wise and column-wise sorted matrix has elements arranged in ascending order both horizontally (across rows) and vertically (down columns). This creates a special structure that allows for efficient searching algorithms beyond simple linear traversal.

The most straightforward approach is to treat the sorted 2D matrix as a flattened 1D array and apply binary search. Since elements maintain sorted order when concatenated row by row, we can use index mapping to convert 1D positions back to 2D coordinates.

Syntax

Following is the syntax for converting between 1D and 2D indices in a matrix −

// Convert 1D index to 2D coordinates
int row = index / numberOfColumns;
int col = index % numberOfColumns;

// Access matrix element
int element = matrix[row, col];

Using Binary Search Approach

The binary search approach treats the matrix as a sorted 1D array by mapping indices. This provides O(log(M×N)) time complexity, which is significantly better than the O(M×N) linear search.

Matrix to 1D Array Mapping 1 2 3 4 5 6 7 8 9 10 11 12 ? 1 2 3 4 5 6 7 8 9 10 11 12

Example

using System;

public class Matrix {
    public bool SearchRowwiseColumnWiseMatrix(int[,] mat, int searchElement) {
        int col = getMatrixColSize(mat);
        int start = 0;
        int last = mat.Length - 1;
        
        while (start <= last) {
            int mid = start + (last - start) / 2;
            int mid_element = mat[mid / col, mid % col];
            
            if (searchElement == mid_element) {
                return true;
            }
            else if (searchElement < mid_element) {
                last = mid - 1;
            }
            else {
                start = mid + 1;
            }
        }
        return false;
    }
    
    private int getMatrixRowSize(int[,] mat) {
        return mat.GetLength(0);
    }
    
    private int getMatrixColSize(int[,] mat) {
        return mat.GetLength(1);
    }
}

class Program {
    static void Main(string[] args) {
        Matrix m = new Matrix();
        int[,] mat = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
        
        Console.WriteLine("Searching for 11: " + m.SearchRowwiseColumnWiseMatrix(mat, 11));
        Console.WriteLine("Searching for 15: " + m.SearchRowwiseColumnWiseMatrix(mat, 15));
        Console.WriteLine("Searching for 1: " + m.SearchRowwiseColumnWiseMatrix(mat, 1));
    }
}

The output of the above code is −

Searching for 11: True
Searching for 15: False
Searching for 1: True

Using Staircase Search Algorithm

An alternative approach is the staircase search, which starts from the top-right corner and moves either left or down based on comparisons. This provides O(M+N) time complexity.

Example

using System;

public class MatrixStaircaseSearch {
    public bool SearchMatrix(int[,] mat, int target) {
        int rows = mat.GetLength(0);
        int cols = mat.GetLength(1);
        
        int row = 0;
        int col = cols - 1;
        
        while (row < rows && col >= 0) {
            if (mat[row, col] == target) {
                Console.WriteLine($"Element found at position ({row}, {col})");
                return true;
            }
            else if (mat[row, col] > target) {
                col--; // Move left
            }
            else {
                row++; // Move down
            }
        }
        return false;
    }
}

class Program {
    static void Main(string[] args) {
        MatrixStaircaseSearch search = new MatrixStaircaseSearch();
        int[,] mat = new int[4, 4] { 
            { 1, 4, 7, 11 }, 
            { 2, 5, 8, 12 }, 
            { 3, 6, 9, 16 }, 
            { 10, 13, 14, 17 } 
        };
        
        Console.WriteLine("Matrix:");
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                Console.Write(mat[i, j] + "\t");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
        
        Console.WriteLine("Searching for 5: " + search.SearchMatrix(mat, 5));
        Console.WriteLine("Searching for 15: " + search.SearchMatrix(mat, 15));
    }
}

The output of the above code is −

Matrix:
1	4	7	11	
2	5	8	12	
3	6	9	16	
10	13	14	17	

Element found at position (1, 1)
Searching for 5: True
Searching for 15: False

Comparison of Search Algorithms

Algorithm Time Complexity Space Complexity Approach
Linear Search O(M × N) O(1) Check every element
Binary Search O(log(M × N)) O(1) Treat as 1D sorted array
Staircase Search O(M + N) O(1) Start from corner, eliminate row/column

Conclusion

For searching in row-wise and column-wise sorted matrices, binary search offers the best time complexity at O(log(M×N)), while staircase search provides an intuitive O(M+N) solution. Both approaches significantly outperform linear search and are well-suited for different scenarios depending on matrix dimensions and search frequency.

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

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements