Javatpoint Logo
Javatpoint Logo

Search in a row wise and column wise sorted matrix

Introduction

A basic computer science problem, searching for elements in matrices is essential to many applications, from image processing to databases. We can use more sophisticated search techniques to maximize the process when faced with a matrix that is sorted both in rows and columns. We will examine the complexities of searching in a sorted matrix both row-wise and column-wise, examining both simple and complex algorithms to find the best answers.

Consider a two-dimensional matrix with ascending order for each row and column. This unusual structure provides a wealth of exploration opportunities and challenges that require creative search algorithms. In such matrices, conventional search techniques, such as the linear search, are intrinsically inefficient. Developers, therefore, resort to more advanced techniques that take advantage of the sorted nature of the matrix.

Algorithm for Searching in a Row-Wise and Column-Wise Sorted Matrix

Start from the top-right corner of the matrix

Start your search from the element in the matrix's upper-right corner. The reason this corner was selected is that it makes it possible to remove rows or columns according to the desired value effectively.

Return the element's position if it matches the target

Verify that the target and the current element in the matrix match. If so, the target's position has been found, and the search was successful. Either mark the position as found or return it.

If the current element is greater than the target, move left

It is implied that all of the elements in the current column are greater if the current element exceeds the target. To investigate smaller values in the same row, proceed left.

Proceed downward if the current element is less than the desired amount

All of the elements in the current row are smaller if the current element is less than the target. To investigate larger values in the same column, descend.

Until the target is located or you cross the boundary, repeat steps 2-4

Repeat steps 2 through 4 until the target is located, or the search is no longer valid. Reaching the left or bottom edge of the matrix indicates that the target is not in the matrix, which is known as going out of bounds.

The Brute Force Approach

The simplest technique for finding a target element in a matrix is the brute force method. This method entails going over each matrix element one by one until the target is located. Although this method has a time complexity of O(m * n), where m is the number of rows and n is the number of columns, there are more efficient options, especially for large matrices.

Code

Output:

Search in a row wise and column wise sorted matrix

Code Explanation

The searchMatrixBruteForce function

  • Parameters: An integer target that represents the value to be searched and a 2D array matrix that represents the matrix are provided to the function.
  • Return Type: If the target is located, it returns an integer; if not, it returns 0.

Main Function (main)

  • Initialization of the Matrix: Initial values for a 4x4 matrix called matrix are integers.
  • Target Value: The value to be searched in the matrix is represented by the integer variable target, which has been set to 5.
  • Function Call: The matrix and target are passed as arguments to the searchMatrixBruteForce function.
  • Output: The program prints whether or not the target was found based on the outcome.

Brute Force Method (searchMatrixBruteForce)

To iterate over each matrix element, the searchMatrixBruteForce function employs a nested loop. It determines whether the target value and the current element are equal. The function returns 1 if a match is found, meaning that the target is in the matrix. The function returns 0 to indicate that the target is not present if, after iterating through the entire matrix, no match is found.

Time Complexity

The searchMatrixBruteForce function has an O(m * n) time complexity, where'm' denotes the number of rows and 'n' the number of columns in the matrix. This is due to the fact that the code iterates through each matrix element using nested loops, requiring that, in the worst scenario, each element be checked.

Space Complexity

Regardless of the size of the input, the algorithm requires a fixed amount of additional space; hence, the space complexity is O(1). The target, the result, and the loop counters (i and j) are the only variables that are used. The amount of space needed for these variables is constant and does not increase as the size of the input matrix does.

Binary Search Approach

Finding an element in a matrix that is sorted both column- and row-wise offers a different set of possibilities and difficulties. Although the brute force method can be simple, it could be more efficient when dealing with larger matrices. This is where the Binary Search Approach helps, offering an optimal solution that makes use of the matrix's sorted structure. By repeatedly dividing the search space in half, binary search is a traditional algorithmic technique that finds a target element in a sorted collection with efficiency. Binary search can dramatically reduce the number of comparisons required when applied to a row-wise and column-wise sorted matrix, resulting in a time complexity of O(m + n), where m is the number of rows and n is the number of columns.

How Binary Search Works in a Sorted Matrix

Initialize Pointers: Pointers should be initialized by setting them to the matrix's upper-right corner or any other sensible starting point. For instance, set col to cols - 1 and row to 0.

Compare with Target: Make a comparison between the target and the element at its current position.

Adjust Pointers: Pointers should be adjusted by moving left if the current element is greater than the target or down if it is less than the target, depending on the comparison.

Repeat: Until the target is located or the pointers cross the boundary, repeat steps 2 and 3 as necessary.

Code

Output:

Search in a row wise and column wise sorted matrix

Code Explanation

Function (searchMatrixBinary) Definition

  • To conduct a binary search in a matrix that has been sorted both row-wise and column-wise, the searchMatrixBinary function is defined.
  • Its parameters are an integer target and a 2D array matrix.
  • In this example, the matrix is assumed to have dimensions of 4x4 (rows = 4, cols = 4).
  • If the target is located, the function returns 1, and if not, it returns 0.

Setting up the main function

  • A 4x4 matrix named matrix is initialized with example values by the main function.
  • There is a 5 set as the target element to search for.

Function Call(searchMatrixBinary)

  • The supplied matrix and target are passed as arguments to the searchMatrixBinary function.
  • The outcome is kept in the result variable.

Output

  • Based on the value of the result, the program then prints whether or not the target is found in the matrix.

Time Complexity

The code has an O(m + n) time complexity, where m denotes the number of rows and n is the number of columns in the matrix. This is because, depending on how the target and the current matrix element compare, either a row or a column is removed during each iteration of the while loop. The algorithm will, in the worst scenario, only go through each row and column once, resulting in a linear time complexity.

Space Complexity

The code has an O(1) space complexity. Regardless of the size of the input matrix, the algorithm always uses the same amount of space. Integers for the indices (row and col) and the current element (currentElement) are the only variables used. The algorithm does not employ any additional data structures that scale with the size of the input; instead, these variables occupy constant space.


Next TopicSIP Stack





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA




news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news
news