We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Searching Algorithms for 2D Arrays (Matrix)
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
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 a2D 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:
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.
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)