Just an idea, since the array is ordered. Consider comparing the
mid of the array. If the number X is greater than the mid, then
compare the mid of the top half. Keep this pattern. As soon as you
have failed 2 greater than comparison, then start with the subList thats
being considered and brute force it. That way, the the search
could be in log(n) at worst.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
google for binary search algorithms.
[edit]Oops! Didn't see firstPerson's response.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
So far so good. But you still underuse the second chance. Say, you work your way up with an increment of K. The worst case will give you (N/K) + K comparisons. Which value of K will minimize it?
It is not the best algorithm, but is very close to the best (at least, it gives the right asymptotic behaviour). What's left is (a) to make the increment vary according to the amount of yet untested values, and (b) to prove that it is actually the best.
Good luck.
PS to those who answered before me. The wording of the original problem statement is very confusing. Please reread it carefully. It is a very well-known interview problem, usually formulated as follows:
You are given 2 marbles and a skyscraper. Determine a lowest story, such that marble breaks when dropped from it.
A binary search does not work here.
I wasn't implying full binary search, just a partial binary search.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608