It seems that the elements in the 2d array (be [n] [m]) grow horizontally and vertically. Therefore, for this question, we need to first find the index of the element. Therefore, if we can find the element faster, we can optimize the solution. The question is how do we find it in an effective way. One approach is to take the middle element of the matrix and check this element with it
if this element is smaller than the middle element, then our solution lies in the matrix a [0] [0] on [n / 2] [m / 2], since all the elements on the right and bottom are larger than the average (since this element is smaller than the middle element), therefore, we reduced our search space from [n] [m] to [n / 2] [m / 2], which is one quarter of the original size.
if this element is larger than the middle element, then our solution does not lie in the matrices a [0] [0] to [n / 2] [m / 2], because all the elements on the left and on the top are smaller than the average (since this element is larger than the middle element ), so our search space is a full array minus [0] [0] by [n / 2] [m / 2], which is three-quarters of the original size. A common array minus a [0] [0] to [n / 2] [m / 2] means there will be three recursive calls with the index of the array
--------->a[0][m/2](start index) to a[n/2][m](end index) --------->a[n/2][0](start index) to a[n][m/2](end index) --------->a[n/2][m/2](start index) to a[n][m](end index)
Now recursively call the same function as in our search space.
The time complexity of our function will be next. NOTE:. The time function n represents the total number of elements, but not the number of rows, as indicated. n = (no_of_rows) * (no_of_columns)
_________________T(n/4) if given element is less than middle of the array. / / T(n)==========------------------- 1 if n=1 (if element found) \ \_________________3T(n/4) if given element is greater than middle element of array
so the timeout function will be
T (n) = 3T (n / 4) or T (n) = T (n / 4)
In worst case T(n)=3T(n/4) T(n)=3{3T(n/4)} T(n)=3power(i)T(n/(4)poweri) equation------> (1)
But T (1) = 1 (guessing the given element is found in the array)
so n/(4power(i))=1 ====> n=2power(2*i) ====> n=2power(2*i)
Talking log with base 2 on both sides (log[n])/2=i ====> i = log (sqrt (n))
substituting equation 1, we obtain T (n) = 3power (log [sqrt (n)])
So, after finding the element using the index, we can find its neighbors. Let's say the item is found in [i] [j], then type
{ a[i-1][j-1], a[i-1][j], a[i-1][j+1], a[i][j-1], a[i][j+1], a[i+1][j-1], a[i+1][j], a[i+1][j+1] }
on condition,
0<i<n and 0<j<n .