Search a sorted 2D matrix [duplicate]

init: m[1..n(rows),1….m(columns)]

i=n,j=1

Start at (i,j):

STEP 1) if the value equals m(i,j) return (i,j)
STEP 2) if the value > m(i,j) go to step 1 with j+=1
STEP 3) else go to step 1 with i-=1

at each step if j or i is out of bound return no-solution.

The complexity of this solution is O(n+m) in case n=m the complexity is O(n)

I wonder if there is a log(n*m) solution like in binary search

EDIT another possible solution:

STEP 1)take the middle (n/2,m/2) of the matrix and compare it to the value
STEP 2) if the value equals m(i,j) return (i,j)
STEP 3) if the value is higher you can get rid from the first quarter  
STEP 4) if the value is lower you can get rid from the forth quarter
STEP 5) split the 3 other quarters to 2, a rectangle and a box, 
        send those both items to step 1 in a recursive manner

I am not sure about the efficiency of this solution:
if R = N*M then T(R) = T(R/2) + T(R/4) + O(1)

Leave a Comment