You Do Not Really Understand Something Unless You Can Explain It To Your Grandmother
The document discusses calculating the midpoint of a range for binary search. It recommends using mid = lo + (hi-lo+1)/2 instead of mid = lo + (hi-lo)/2 to avoid rounding issues. It also suggests testing code on a two-element set where the first element returns false and the second returns true, and terminating the search when the space is smaller than a predetermined bound like 10^12 or after a fixed number of iterations like a few hundred.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
36 views1 page
You Do Not Really Understand Something Unless You Can Explain It To Your Grandmother
The document discusses calculating the midpoint of a range for binary search. It recommends using mid = lo + (hi-lo+1)/2 instead of mid = lo + (hi-lo)/2 to avoid rounding issues. It also suggests testing code on a two-element set where the first element returns false and the second returns true, and terminating the search when the space is smaller than a predetermined bound like 10^12 or after a fixed number of iterations like a few hundred.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1
You do not really understand something unless you can explain it to your
grandmother.
The solution is to change mid = lo + (hi-lo)/2 to mid = lo + (hi-lo+1)/2, i.e. so that it
rounds up instead of down. There are other ways of getting around the problem, but this one is possibly the cleanest. Just remember to always test your code on a two-element set where the predicate is false for the first element and true for the second. why mid is calculated using mid = lo + (hi-lo)/2 instead of the usual mid = (lo+hi)/2. This is to avoid another potential rounding bug: in the first case, we want the division to always round down, towards the lower bound. But division truncates, so when lo+hi would be negative, it would start rounding towards the higher bound. terminate when the search space gets smaller than some predetermined bound (say 10 12 ) or do a fixed number of iterations. On TopCoder, your best bet is to just use a few hundred iterations, this will give you the best possible precision without too much thinking. 100 iterations will reduce the search space to approximately 10 -30 of its initial size, which should be enough for most (if not all) problems.