Open In App

Searching Algorithms for 2D Arrays (Matrix)

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Linear Search in 2D Array:

Linear search is a simple and sequential searching algorithm. It is used to find whether a particular element is present in the array or not by traversing every element in the array. While searching in the 2D array is exactly the same but here all the cells need to be traversed In this way, any element is searched in a 2D array. 

Below is the implementation for linear search in 2D arrays

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
vector<int> linearSearch(vector<vector<int>> arr, int target)
{
  for (int i = 0; i < arr.size(); i++) {
    for (int j = 0; j < arr[i].size(); j++) {
      if (arr[i][j] == target) {
        return {i, j};
      }
    }
  }
  return {-1, -1};
}
 
// Driver code
int main()
{
 
  vector<vector<int>> arr = { { 3, 12, 9 },
                             { 5, 2, 89 },
                             { 90, 45, 22 } };
  int target = 89;
  vector<int> ans = linearSearch(arr, target);
  cout << "Element found at index: [" << ans[0] << " " <<ans[1] <<"]";
 
  return 0;
}
 
// This code is contributed by Potta Lokesh


Java




// Linear Search in 2D arrays
import java.util.Arrays;
 
public class GFG {
    public static void main(String[] args)
    {
        int arr[][] = { { 3, 12, 9 },
                        { 5, 2, 89 },
                        { 90, 45, 22 } };
        int target = 89;
        int ans[] = linearSearch(arr, target);
        System.out.println("Element found at index: "
                           + Arrays.toString(ans));
    }
 
    static int[] linearSearch(int[][] arr, int target)
    {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] == target) {
                    return new int[] { i, j };
                }
            }
        }
        return new int[] { -1, -1 };
    }
}


Python3




# Python code for the above approach
def linearSearch (arr, target):
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            if (arr[i][j] == target):
                return [i, j]
    return [-1, -1]
 
# Driver code
arr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]
target = 89
ans = linearSearch(arr, target)
print(f"Element found at index: [{ans[0]} {ans[1]}]")
 
# This code is contributed by Saurabh Jaiswal


C#




// Linear Search in 2D arrays
using System;
 
public class GFG {
    public static void Main(string[] args)
    {
        int[, ] arr = { { 3, 12, 9 },
                        { 5, 2, 89 },
                        { 90, 45, 22 } };
        int target = 89;
        int[] ans = linearSearch(arr, target);
        Console.WriteLine("Element found at index: ["
                          + ans[0] + "," + ans[1]+"]");
    }
 
    static int[] linearSearch(int[, ] arr, int target)
    {
        for (int i = 0; i < arr.GetLength(0); i++) {
            for (int j = 0; j < arr.GetLength(1); j++) {
                if (arr[i, j] == target) {
                    return new int[] { i, j };
                }
            }
        }
        return new int[] { -1, -1 };
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
    // JavaScript code for the above approach
    const linearSearch = (arr, target) => {
        for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < arr[i].length; j++) {
                if (arr[i][j] == target) {
                    return [i, j];
                }
            }
        }
        return [-1, -1];
    }
 
    // Driver code
    let arr = [[3, 12, 9],
    [5, 2, 89],
    [90, 45, 22]];
    let target = 89;
    let ans = linearSearch(arr, target);
    document.write(`Element found at index: [${ans[0]} ${ans[1]}]`);
 
    // This code is contributed by rakeshsahni
 
</script>


Output

Element found at index: [1 2]

Time Complexity: O (N * M), where N is the number of rows and M is the number of columns.
Auxiliary Space: O(1)

Binary Search in a 2D Array: 

Binary search is an efficient method of searching in an array. Binary search works on a sorted array. At each iteration the search space is divided in half, this is the reason why binary search is more efficient than linear search. 

Why Binary Search is not useful for searching in unsorted arrays?

The basic condition to apply Binary Search anywhere in any algorithm is that the search space should be sorted. To perform a Binary search in the 2D array, the array needs to be sorted. Here is an unsorted 2D array is given, so applying Binary Search in an unsorted array is not possible. To apply Binary Search first the 2D array needs to be sorted in any order that itself takes (M*N)log(M*N) time. So the total time complexity to search any element here is O((M * N) log(M * N)) + O(N + M) which very poor when it is compared with the time complexity of Linear Search which is just O(N*M). Therefore, Linear Search is used for searching in an unsorted array, not Binary Search.

Below is the implementation for Binary search in 2D arrays:

C++




// Binary Search on sorted 2D array
#include <bits/stdc++.h>
using namespace std;
 
vector<int> findAns(vector<vector<int> > arr, int target)
{
    int row = 0;
    int col = arr[row].size() - 1;
    while (row < arr.size() && col >= 0) {
        if (arr[row][col] == target) {
            return { row, col };
        }
 
        // Target lies in further row
        if (arr[row][col] < target) {
            row++;
        }
        // Target lies in previous column
        else {
            col--;
        }
    }
    return { -1, -1 };
}
 
// Driver Code
int main()
{
 
    // Binary search in sorted matrix
    vector<vector<int> > arr = { { 1, 2, 3, 4 },
                                 { 5, 6, 7, 8 },
                                 { 9, 10, 11, 12 } };
 
    vector<int> ans = findAns(arr, 12);
 
    cout << "Element found at index: [";
    for (int i = 0; i < ans.size(); i++) {
        if (i == ans.size() - 1)
            cout << ans[i];
        else
            cout << ans[i] << ", ";
    }
    cout << "]";
}
 
// This code is contributed by Samim Hossain Mondal.


Java




// Binary Search on sorted 2D array
import java.util.Arrays;
 
class GFG {
 
    static int[] findAns(int[][] arr, int target)
    {
        int row = 0;
        int col = arr[row].length - 1;
        while (row < arr.length && col >= 0) {
            if (arr[row][col] == target) {
                return new int[] { row, col };
            }
 
            // Target lies in further row
            if (arr[row][col] < target) {
                row++;
            }
            // Target lies in previous column
            else {
                col--;
            }
        }
        return new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Binary search in sorted matrix
        int arr[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 } };
        int[] ans = findAns(arr, 12);
        System.out.println("Element found at index: "
                           + Arrays.toString(ans));
    }
}


Python3




# Binary Search on sorted 2D array
def findAns(arr, target):
    row = 0
    col = len(arr[row]) - 1
    while (row < len(arr) and col >= 0):
        if (arr[row][col] == target):
            return [row, col]
 
        # Target lies in further row
        if (arr[row][col] < target):
            row += 1
 
        # Target lies in previous column
        else:
            col -= 1
 
    return [-1, -1]
 
 
# Driver Code
if __name__ == '__main__':
    # Binary search in sorted matrix
    arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
    ans = findAns(arr, 12)
    print("Element found at index: ", ans)
 
    # This code contributed by shikhasingrajput


C#




// Binary Search on sorted 2D array
using System;
class GFG {
 
    static int[] findAns(int[, ] arr, int target)
    {
        int row = 0;
        int col = arr.GetLength(1) - 1;
        while (row < arr.GetLength(0) && col >= 0) {
            if (arr[row, col] == target) {
                return new int[] { row, col };
            }
 
            // Target lies in further row
            if (arr[row, col] < target) {
                row++;
            }
 
            // Target lies in previous column
            else {
                col--;
            }
        }
        return new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        // Binary search in sorted matrix
        int[, ] arr = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 } };
        int[] ans = findAns(arr, 12);
        Console.Write("Element found at index: [");
        int i = 0;
        for (i = 0; i < ans.Length - 1; i++)
            Console.Write(ans[i] + " ,");
        Console.Write(ans[i] + "]");
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
// Binary Search on sorted 2D array
   function findAns(arr , target)
    {
        var row = 0;
        var col = arr[row].length - 1;
        while (row < arr.length && col >= 0) {
            if (arr[row][col] == target) {
                return [ row, col ];
            }
 
            // Target lies in further row
            if (arr[row][col] < target) {
                row++;
            }
             
            // Target lies in previous column
            else {
                col--;
            }
        }
        return [ -1, -1 ];
    }
 
    // Driver Code
    // Binary search in sorted matrix
        var arr = [ [ 1, 2, 3, 4 ],
                        [ 5, 6, 7, 8 ],
                        [ 9, 10, 11, 12 ] ];
        var ans = findAns(arr, 12);
        document.write("Element found at index: "
                           + (ans));
                            
// This code is contributed by shikhasingrajput
</script>


Output

Element found at index: [2, 3]

Time Complexity: O(N + M), where N is the number of rows and M is the number of columns.
Auxiliary Space: O(1)

Improved Binary Search in a 2D Array: 

We can reduce the time by converting 2D array to 1D array. Add row one after another and search the item then convert it to 2D again.

1 2 3
4 5 6
7 8 9

Convert it to 1D array 

1 2 3 4 5 6 7 8 9

Now apply normal binary search and get the result. Not necessary store the 1D in new array you can create it virtually by converting row, col value to 1D index vice-versa 1D to row, col value.   

C++




// Binary Search on sorted 2D array
#include <bits/stdc++.h>
using namespace std;
 
vector<int> findAns(vector<vector<int> > arr, int target)
{
  int row = arr.size();
  int col = arr[0].size();
  int l = 0, h = row * col - 1;
 
  while (l <= h) {
    int mid = l + (h - l) / 2;
 
    int tC = mid % col;
    int tR = mid / col;
    int val = arr[tR][tC];
    if (val == target)
      return { tR, tC };
 
    if (val < target)
      l = mid + 1;
    else
      h = mid - 1;
  }
 
  return { -1, -1 };
}
 
int main()
{
 
  // Binary search in sorted matrix
  vector<vector<int> > arr = { { 1, 2, 3, 4 },
                              { 5, 6, 7, 8 },
                              { 9, 10, 11, 12 } };
 
  vector<int> ans = findAns(arr, 12);
 
  cout << "Element found at index: [";
  for (int i = 0; i < ans.size(); i++) {
    if (i == ans.size() - 1)
      cout << ans[i];
    else
      cout << ans[i] << ", ";
  }
  cout << "]";
  return 0;
}
 
// This code is contributed by lokeshmvs21.


Java




// Binary Search on sorted 2D array
import java.util.Arrays;
 
class GFG {
 
    static int[] findAns(int[][] arr, int target)
    {
        int row = arr.length;
        int col = arr[0].length;
        int l = 0, h = row * col - 1;
 
        while (l <= h) {
            int mid = l + (h - l) / 2;
 
            int tC = mid % col;
            int tR = mid / col;
            int val = arr[tR][tC];
            if (val == target)
                return new int[] { tR, tC };
 
            if (val < target)
                l = mid + 1;
            else
                h = mid - 1;
        }
 
        return new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Binary search in sorted matrix
        int arr[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 } };
        int[] ans = findAns(arr, 12);
        System.out.println("Element found at index: "
                           + Arrays.toString(ans));
    }
}


Python3




# Python code for binary search on sorted 2D array
def findAns(arr, target):
    row = len(arr)
    col = len(arr[0])
    l, h = 0, row*col - 1
 
    while(l <= h):
        mid = l + (h-l)//2
 
        tC = mid % col
        tR = mid // col
        val = arr[tR][tC]
        if(val == target):
            return [tR, tC]
        if(val < target):
            l = mid + 1
        else:
            h = mid - 1
 
    return [-1, -1]
 
# Binary search in sorted matrix
arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
ans = findAns(arr, 12)
print("Element found at index:", ans)
 
# This code is contributed by lokesh


C#




// Binary Search on sorted 2D array
using System;
 
public class GFG {
 
  static int[] findAns(int[, ] arr, int target)
  {
    int row = arr.GetLength(0);
    int col = arr.GetLength(1);
    int l = 0, h = row * col - 1;
 
    while (l <= h) {
      int mid = l + (h - l) / 2;
 
      int tC = mid % col;
      int tR = mid / col;
      int val = arr[tR, tC];
      if (val == target)
        return new int[] { tR, tC };
 
      if (val < target)
        l = mid + 1;
      else
        h = mid - 1;
    }
 
    return new int[] { -1, -1 };
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Binary search in sorted matrix
    int[, ] arr = new int[, ] { { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 } };
    int[] ans = findAns(arr, 12);
    Console.WriteLine("Element found at index: ["
                      + string.Join(", ", ans) + "]");
  }
}
 
// This code is contributed by karndeep11234.


Javascript




// Binary Search on sorted 2D array
 
function findAns( arr, target)
{
  let row = arr.length;
  let col = arr[0].length;
  let l = 0, h = row * col - 1;
 
  while (l <= h) {
    let mid = l + Math.floor((h - l) / 2);
 
    let tC = mid % col;
    let tR = Math.floor(mid / col);
    let val = arr[tR][tC];
    if (val == target)
      return [ tR, tC ];
 
    if (val < target)
      l = mid + 1;
    else
      h = mid - 1;
  }
 
  return [ -1, -1 ];
}
 
 
  // Binary search in sorted matrix
  let arr = [ [ 1, 2, 3, 4 ],
                              [5, 6, 7, 8 ],
                              [ 9, 10, 11, 12 ]];
 
  let ans = findAns(arr, 12);
 
  let print = "Element found at index: [";
  for (let i = 0; i < ans.length; i++) {
    if (i == ans.length - 1)
      print+= ans[i];
    else
      print+= ans[i] + ", ";
  }
  print+="]";
  console.log(print);
 
// This code is contributed by akashish__


Output

Element found at index: [2, 3]

Time Complexity: O(log N*M), where N is the number of rows and M is the number of columns since binary search will take the whole size of 1d array and here total elements in 2d array = M*N.
Auxiliary Space: O(1)



Similar Reads

Searching Algorithms in Java
Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories: Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear S
5 min read
Difference between Searching and Sorting Algorithms
Prerequisite: Searching and Sorting Algorithms Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is used. Based on the type of operations these algorithms are generally classified into two categories: Sequential Search: The Sequential Search is the basic and simple Searching Algorithm.
4 min read
Searching Algorithms
Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. These algorithms are designed to efficiently navigate through data structures to find the desired information, making them fundamental in various applications such as databases, web search engines, and more. Table of Content What
5 min read
Searching Algorithms in Python
Searching algorithms are fundamental techniques used to find an element or a value within a collection of data. In this tutorial, we'll explore some of the most commonly used searching algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation Search, and Jump Search. 1. Linear SearchLinear search is the simplest sea
6 min read
Rabin-Karp algorithm for Pattern Searching in Matrix
Given matrices txt[][] of dimensions m1 x m2 and pattern pat[][] of dimensions n1 x n2, the task is to check whether a pattern exists in the matrix or not, and if yes then print the top most indices of the pat[][] in txt[][]. It is assumed that m1, m2 ? n1, n2 Examples: Input: txt[][] = {{G, H, I, P} {J, K, L, Q} {R, G, H, I} {S, J, K, L} } pat[][]
15+ min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Iterative searching in Binary Search Tree
Given a binary search tree and a key. Check the given key exists in BST or not without recursion. Please refer binary search tree insertion for recursive search. C/C++ Code // C++ program to demonstrate searching operation // in binary search tree without recursion #include &lt;bits/stdc++.h&gt; using namespace std; struct Node { int data; struct N
7 min read
Pattern Searching using C++ library
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n &gt; m.Examples: Input : txt[] = "geeks for geeks" pat[] = "geeks" Output : Pattern found at index 0 Pattern found at index 10 Input : txt[] = "aaaa" pat[] = "aa" Output : Pattern found at index 0 Pattern found a
3 min read
Array range queries for searching an element
Given an array of N elements and Q queries of the form L R X. For each query, you have to output if the element X exists in the array between the indices L and R(included). Prerequisite : Mo's Algorithms Examples : Input : N = 5 arr = [1, 1, 5, 4, 5] Q = 3 1 3 2 2 5 1 3 5 5 Output : No Yes Yes Explanation : For the first query, 2 does not exist bet
15+ min read
three90RightbarBannerImg