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.
Yes, your solution seems correct and efficient (given your description of the initial problem, they probably want you to use binary search). Your algorithm should go something like this:
where binary search can be implemented according to the pseudocode found here: http://en.wikipedia.org/wiki/Binary_search_algorithm#Recursive