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 Java implementation of above algorithm.
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)
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.
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
- Median of two sorted arrays of same size
- Count Inversions in an array | Set 1 (Using Merge Sort)
- Maximum and minimum of an array using minimum number of comparisons
- Check for Majority Element in a sorted array
- Program to count number of set bits in an (big) array
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Median of two sorted arrays of different sizes
- Divide and Conquer Algorithm | Introduction
- Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
- Closest Pair of Points using Divide and Conquer algorithm
- Maximum Subarray Sum using Divide and Conquer algorithm
- Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
- Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)