

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to search in a row wise increased matrix using C#?
The primitive solution for this problem is to scan all elements stored in the input matrix to search for the given key. This linear search approach costs O(MN) time if the size of the matrix is MxN.
The matrix needs to be scanned from the top right, if the search element is greater than the top right element then increments the row or else decrement the column. The below piece of code develops a function SearchRowwiseIncrementedMatrix that takes a two-dimensional array and search key as input and returns either true or false depending upon the success or failure of search key found.
Code
public class Matrix{ public bool SearchRowwiseIncrementedMatrix(int[,] mat, int searchElement){ int row = getMatrixRowSize(mat); int col = getMatrixColSize(mat) - 1; int r = 0; while (col >= 0 && r < row){ if (mat[r, col] == searchElement){ return true; } else if (searchElement < mat[r, col]){ col--; } else{ r++; } } return false; } private int getMatrixRowSize(int[,] mat){ return mat.GetLength(0); } private int getMatrixColSize(int[,] mat){ return mat.GetLength(1); } } static void Main(string[] args){ Matrix m = new Matrix(); int[,] mat = new int[3, 4] { { 1, 7, 10, 19 }, { 2, 8, 11, 20 }, { 3, 9, 12, 21 } }; Console.WriteLine(m.SearchRowwiseIncrementedMatrix(mat, 11)); }
Output
TRUE
- Related Questions & Answers
- How to search in a row wise and column wise increased matrix using C#?
- Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix using Python?
- Row-wise vs column-wise traversal of matrix in C++
- How to find the row-wise mode of a matrix in R?
- Find median in row wise sorted matrix in C++
- How to find the row-wise index of non-NA values in a matrix in R?
- Row-wise common elements in two diagonals of a square matrix in C++
- How to multiply corresponding row values in a matrix with single row matrix in R?
- How to create a subset of a matrix in R using row names?
- Find a common element in all rows of a given row-wise sorted matrix in C++
- How to multiply single row matrix and a square matrix in R?
- How can a specific operation be applied row wise or column wise in Pandas Python?
- How to remove a row from matrix in R by using its name?
- How to convert the row values in a matrix to row percentage in R?
- Search a string in Matrix Using Split function in Java
Advertisements