How do I search for a number in a 2d array sorted left to right and top to bottom?

后端 未结 20 1008
暖寄归人
暖寄归人 2020-11-22 13:03

I was recently given this interview question and I\'m curious what a good solution to it would be.

Say I\'m given a 2d array where all the numbers i

20条回答
  •  暖寄归人
    2020-11-22 13:29

    I have a recursive Divide & Conquer Solution. Basic Idea for one step is: We know that the Left-Upper(LU) is smallest and the right-bottom(RB) is the largest no., so the given No(N) must: N>=LU and N<=RB

    IF N==LU and N==RB::::Element Found and Abort returning the position/Index If N>=LU and N<=RB = FALSE, No is not there and abort. If N>=LU and N<=RB = TRUE, Divide the 2D array in 4 equal parts of 2D array each in logical manner.. And then apply the same algo step to all four sub-array.

    My Algo is Correct I have implemented on my friends PC. Complexity: each 4 comparisons can b used to deduce the total no of elements to one-fourth at its worst case.. So My complexity comes to be 1 + 4 x lg(n) + 4 But really expected this to be working on O(n)

    I think something is wrong somewhere in my calculation of Complexity, please correct if so..

提交回复
热议问题