Searching Algorithms for 2D Arrays (Matrix)

27 Dec, 2021
Linear Search in 2D Array
Linear search is a simple and sequential searching algorithm. It is used to find 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 and In this way, any element is searched in a 2D array. 
Below is the implementation for linear search in 2D arrays
C++
Java
Python3
C#
Javascript
// 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 codeint 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
// Linear Search in 2D arraysimport 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 };    }}
# Python code for the above approachdef 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 codearr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]target = 89ans = linearSearch(arr, target)print(f"Element found at index: [{ans[0]} {ans[1]}]") # This code is contributed by Saurabh Jaiswal
// Linear Search in 2D arraysusing 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.
<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>
  
Element found at index: [1, 2]
 
The Time Complexity of linear search in a 2D array is O (N * M) where N is the number of rows and M is the number of columns.
 
Binary Search in a 2D Array
 
Binary search is an efficient method of searching in an array. Binary search works on 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++
Java
Python3
C#
Javascript
// Binary Search on sorted 2D array#include <bits/stdc++.h>using namespace std; vector<int> findAns(vector<vector<int>> arr, int target){  int r = 0;  int c = arr[r].size() - 1;  while (r < arr.size() && c >= 0) {    if (arr[r] == target) {      return { r, c };    }     // Target lies in further row    if (arr[r] < target) {      r++;    }    // Target lies in previous column    else {      c--;    }  }  return { -1, -1 };} // Driver Codeint 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.
// Binary Search on sorted 2D arrayimport java.util.Arrays; class GFG {     static int[] findAns(int[][] arr, int target)    {        int r = 0;        int c = arr[r].length - 1;        while (r < arr.length && c >= 0) {            if (arr[r] == target) {                return new int[] { r, c };            }             // Target lies in further row            if (arr[r] < target) {                r++;            }            // Target lies in previous column            else {                c--;            }        }        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));    }}
# Binary Search on sorted 2D arraydef findAns(arr, target):    r = 0;    c = len(arr[r]) - 1;    while (r < len(arr) and c >= 0):        if (arr[r] == target):            return [r, c];         # Target lies in further row        if (arr[r] < target):            r += 1;         # Target lies in previous column        else:            c -=1;     return [ -1, -1]; # Driver Codeif __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
// Binary Search on sorted 2D arrayusing System;class GFG {   static int[] findAns(int[, ] arr, int target)  {    int r = 0;    int c = arr.GetLength(1) - 1;    while (r < arr.GetLength(0) && c >= 0) {      if (arr[r, c] == target) {        return new int[] { r, c };      }       // Target lies in further row      if (arr[r, c] < target) {        r++;      }       // Target lies in previous column      else {        c--;      }    }    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.
<script>// Binary Search on sorted 2D array   function findAns(arr , target)    {        var r = 0;        var c = arr[r].length - 1;        while (r < arr.length && c >= 0) {            if (arr[r] == target) {                return [ r, c ];            }             // Target lies in further row            if (arr[r] < target) {                r++;            }                         // Target lies in previous column            else {                c--;            }        }        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>
Element found at index: [2, 3]
The Time Complexity of binary search in an already sorted 2D array is O (N + M) where N is the number of rows and M is the number of columns.
 
lokeshpotta20
rakeshsahni
_saurabh_jaiswal
ukasp
samim2000
shikhasingrajput
Binary Search
Arrays
Matrix
Searching
Arrays
Searching
Matrix
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Longest Consecutive Subsequence
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
Rotate a matrix by 90 degree in clockwise direction without using any extra space