Search in a row-wise and column-wise sorted matrix.Imagine a 2D matrix where each row and each column are sorted in ascending order. This matrix structure presents a challenge when searching for a specific element. Naively applying a linear search would not be efficient as it would disregard the sorted nature of the matrix. To solve this problem, we need to employ a search algorithm that leverages the sorting order to eliminate non-relevant portions of the matrix. Approach: Binary SearchBinary search is a powerful algorithm that can significantly reduce the search space with each iteration. In our case, we can apply binary search twice: once for searching in rows and once for searching in columns. Searching in Rows Let's consider the steps involved in searching for an element target in a particular row of the matrix: Initialize left as the leftmost index of the row and right as the rightmost index. While the left is less than or equal to the right:
If the element is not found in the row, return a special value indicating its absence. Searching in Columns Similarly, the steps for searching for the target in a particular column are as follows: Initialize the top as the topmost index of the column and the bottom as the bottommost index of the column. While the top is less than or equal to the bottom:
If the element is not found in the column, return a special value indicating its absence. Combining the Approaches To perform a search in the matrix, we start from the top-right corner. We compare the element at that position with the target. We have found our element if the element is equal to the target. If it is greater than the target, we move left in the current row. We move down in the current column if it is less than the target. Following these steps, we either find the element or exhaust the search space without success. Implementation in JavaNow that we clearly understand the approach let's implement it in Java. Output: Explanation: The searchInMatrix method takes a sorted matrix and a target value as input.
Time Complexity: The time complexity of the provided search algorithm for a row-wise and column-wise sorted matrix is O(m + n), where 'm' is the number of rows and 'n' is the number of columns in the matrix. |