Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithm
Given an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix.
A linear time complexity is discussed in the previous post. This problem can also be a very good example for divide and conquer algorithms. Following is divide and conquer algorithm.
1) Find the middle element.
2) If middle element is same as key return.
3) If middle element is lesser than key then
….3a) search submatrix on lower side of middle element
….3b) Search submatrix on right hand side.of middle element
4) If middle element is greater than key then
….4a) search vertical submatrix on left side of middle element
….4b) search submatrix on right hand side.
Following implementation of above algorithm.
Found 10 at 0 0 Found 20 at 0 1 Found 30 at 0 2 Found 40 at 0 3 Found 15 at 1 0 Found 25 at 1 1 Found 35 at 1 2 Found 45 at 1 3 Found 27 at 2 0 Found 29 at 2 1 Found 37 at 2 2 Found 48 at 2 3 Found 32 at 3 0 Found 33 at 3 1 Found 39 at 3 2 Found 50 at 3 3
We are given a n*n matrix, the algorithm can be seen as recurring for 3 matrices of size n/2 x n/2. Following is recurrence for time complexity
T(n) = 3T(n/2) + O(1)
Space Complexity: O(log(n))
The solution of recurrence is O(n1.58) using Master Method.
But the actual implementation calls for one submatrix of size n x n/2 or n/2 x n, and other submatrix of size n/2 x n/2.
The approach below is a modified version of the binary search algorithm, called Binary Search on Rows algorithm.
- Loop through each row of the matrix.
- Check if the key falls within the range of the current row (i.e., if the first element of the row is less than or equal to the key and the last element of the row is greater than or equal to the key).
- If the key falls within the range of the current row, perform binary search on that row to find the key.
- If the key is found, print the row and column index of the key and return.
- If the key is not found in any row, print that the key was not found.
implementation of above approach
Found 50 at 3
Time complexity analysis:
In the worst case, we will perform binary search on each of the ROW rows of the matrix. The time complexity of binary search is O(log COL), and we perform it ROW times, so the overall time complexity of the Binary Search on Rows algorithm is O(ROW * log COL). Since the matrix is row-wise and column-wise sorted, we can assume that ROW and COL are roughly the same size, so the time complexity can be simplified to O(N log N), where N = ROW = COL.
This article is contributed by Kaushik Lele. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Please Login to comment...