Add binary-search module: iterative/recursive search, overflow-safe midpoint, lowerBound/upperBound, rotated arrays, search on the answer, 10 interview problems (14 tests, 14 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3tGdV3Vm51QUZxg2x
This commit is contained in:
Claude
2026-11-22 19:47:36 +05:30
parent 3336e2ba15
commit ce12a80f58
39 changed files with 2110 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
The (lo + hi) / 2 bug on a sorted sequence of 2,000,000,000 elements (no array: see Overflow.Sequence)
====================================================================================================
Plain int arithmetic, lo=1000000000 hi=1999999999:
lo + hi = -1294967297
(lo + hi) / 2 = -647483648
lo + (hi - lo) / 2 = 1499999999
(lo + hi) >>> 1 = 1499999999
Broken (lo + hi) / 2, searching for the last element, 1999999999:
lo=0 hi=1999999999 lo+hi=1999999999 mid=999999999
lo=1000000000 hi=1999999999 lo+hi=-1294967297 mid=-647483648
-> java.lang.ArrayIndexOutOfBoundsException: Index -647483648 out of bounds for length 2000000000
Fixed with lo + (hi - lo) / 2: found index 1999999999 after 31 steps. First and last steps:
lo=0 hi=1999999999 hi-lo=1999999999 mid=999999999
lo=1000000000 hi=1999999999 hi-lo=999999999 mid=1499999999
...
lo=1999999999 hi=1999999999 hi-lo=0 mid=1999999999
Fixed with (lo + hi) >>> 1: found index 1999999999