Design an algorithm , FindElement(a,p), where "a" is two-dimensional square array of positive integers with duplicates and each row of integers is in non - decreasing order: a[i][0] ≤ a[i][1] ≤ a[i][2] · · · ≤ a[i][n-1] (i=0,1,. . .,n-1),. The algorithm should define whether or not p is contained in a. It should return true if the "p" was founded, false otherwise. Your algorithm must be as efficient as possible. Algorithm should be based on Binary Search
I have found the following solution (but i'm not sure that it is correct):
Solution is to search for the element working on one row at a time using binary search. Binary searching a given sorted row of size (n) takes O(Log(n)) so it would take O(nlog(n)) to search the entire array in worst case.
Does this solution is suitable for the given task or not? I do not know how to implement this algorithm, please could you give me pseudo - code or explanation how to do it. Thanks in advance.
O(log n). None of the current answers reference this possibility (@Amit's is close, though). This does not necessitate allocating a hash table, or indeed any other variables other than the ones used for anO(n log n)search - you just have to think differently. I'm not revealing the actual answer, because I want you to think of it. Oh, and you don't mention if you need all occurrences, or only one (results quite different).