Binary search Python code you can run
Run binary search Python code and see why its algorithm needs a sorted row.
Published here , updated · 2 sources · Resume reading
Binary search throws away half a sorted row on each midpoint probe [2]. ALGO ARCADE level 7 locates 21 at index 4 in four checks on the shipped corridor list [1][2]. The same loop reports a miss for 50 when the value is absent.
Run the shipped row with print tracing
This matches binary_search() in the level file and uses the demo row from LEVEL.demo [2]:
ROW = [3, 8, 12, 17, 21, 26, 30, 35, 41, 47, 52, 58, 63, 69, 74, 80]
def binary_search(row, target):
lo, hi = 0, len(row) - 1
checks = 0
while lo <= hi:
mid = (lo + hi) // 2
checks += 1
print(f"check {checks}: lo={lo} hi={hi} mid={mid} value={row[mid]}")
if row[mid] == target:
return mid, checks
if row[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1, checks
for target in (21, 50):
idx, n = binary_search(ROW, target)
print(target, "->", idx, f"after {n} checks", "\n")python3 binary_trace.pyCaptured output:
check 1: lo=0 hi=15 mid=7 value=35
check 2: lo=0 hi=6 mid=3 value=17
check 3: lo=4 hi=6 mid=5 value=26
check 4: lo=4 hi=4 mid=4 value=21
21 -> 4 after 4 checks
check 1: lo=0 hi=15 mid=7 value=35
check 2: lo=8 hi=15 mid=11 value=58
check 3: lo=8 hi=10 mid=9 value=47
check 4: lo=10 hi=10 mid=10 value=52
50 -> -1 after 4 checks The module docstring says a sorted million-length row needs about twenty checks because halving continues until one cell remains [2]. On the hit for 21, check 1 discards everything above 35, check 2 discards everything below 17, check 3 discards 26 and above inside the remaining window, and check 4 lands on index 4. Each comparison is a proof about a half of the current interval, not a lucky guess.
Halving only works on ordered values
Each midpoint comparison removes half the interval; that step is valid only when values rise left to right.
The README places binary search after sorting levels because order is what makes the discard step a proof [1]. Shuffle the same sixteen numbers and the midpoint no longer bounds a half that must exclude the target. The loop still returns some index or -1, so the bug looks like a successful run until you check that row[index] == target and that every discarded cell truly could not hold the key.
Linear scan on the same row
ROW = [3, 8, 12, 17, 21, 26, 30, 35, 41, 47, 52, 58, 63, 69, 74, 80]
target = 21
for i, v in enumerate(ROW):
if v == target:
print("linear found at", i, "after", i + 1, "comparisons")
breakpython3 scan_row.pyCaptured output:
linear found at 4 after 5 comparisonsBinary search used four midpoint probes on the same data [2]. The gap widens with length; the docstring's million-entry example is the scaling picture [2]. Linear search is still the right tool for tiny unsorted lists, or when you will search once and never pay for a sort. Binary search wins when the row is already sorted or when you amortize sorting across many queries.
Loop invariants that prevent bugs
while lo <= hi keeps the single-element interval alive. When row[mid] == target, return immediately. When the midpoint is smaller than the target, move lo to mid + 1, not mid, or the loop can stall on the same midpoint forever [2]. When the midpoint is larger, move hi to mid - 1 for the same reason.
Metadata on the level quotes O(log n) time and O(1) extra memory [2]. Best case O(1) happens when the first midpoint is already the answer [2]. Worst case on a sorted row is about floor(log2(n)) + 1 probes for a miss, which is why 50 still took four checks on a length-16 row.
For languages with fixed-width integers, compute mid as lo + (hi - lo) // 2. That form avoids overflow when lo + hi exceeds the type max. Python integers grow as needed, so ALGO ARCADE does not need the guard for demo sizes, but interview ports to C or Java often do [2].
ALGO ARCADE terminal level
git clone https://github.com/kamilikamil/algo-arcade.git
cd algo-arcade
python3 - <<'PY'
from binary_search import binary_search
row = [3, 8, 12, 17, 21, 26, 30, 35, 41, 47, 52, 58, 63, 69, 74, 80]
print("21 ->", binary_search(row, 21))
print("50 ->", binary_search(row, 50))
PYCaptured output:
21 -> 4
50 -> -1The README documents python3 binary_search.py 21 and miss paths such as 50 with stage banners [1][2].
Duplicates, misses, and library bisect
The demo row has unique values. Real logs may repeat. Production code often uses bisect_left to find the first slot at least as large as a key [2]. The arcade routine stops at the first exact hit, which is fine for unique corridor numbers and wrong when you need the leftmost duplicate [2].
A miss still finishes in about log2(n) probes when the value is absent, as the 50 trace shows [2]. After the loop ends with lo > hi, lo is the insertion point for a sorted insert: every index below lo is smaller than the target. That fact is how lower-bound APIs are specified.
messy = [21, 3, 8, 12, 17, 26, 30, 35, 41, 47, 52, 58, 63, 69, 74, 80]
# same loop as binary_trace, target 21Run the same midpoint loop on messy. You may get -1 even though 21 sits at index 0, because early midpoints discard the left side after seeing a value larger than 21 in the "middle" of an unordered row. Blame the precondition, not Python's // operator.
Mistakes that fail interviews
Feeding an unsorted list because it usually works on small data. The algorithm returns an index, but the index is meaningless without order [2].
Choosing while lo < hi and forgetting to test the survivor cell. You get false negatives on single-element rows.
Confusing index with value. The level returns the spot in the corridor, not the enemy strength itself [2].
Calling the complexity O(1) because four checks found 21. Asymptotics describe growth when n changes [2].
Searching after inserts without resorting. Dynamic arrays need a sort step or a tree structure [1].
Off-by-one on mid + 1 / mid - 1. Leaving lo = mid when the midpoint is too small is the classic infinite loop on interviews.
Connect to sorting levels
Bubble sort and heap sort live in the same README arc because binary search consumes sorted output [1]. In application code, sorted() or .sort() is fine; the arcade sorts teach where the ordering invariant comes from.
After search, graph levels such as BFS change the problem shape entirely [1]. Binary search answers "where is this key in an ordered array." BFS answers "what is the fewest hops on a graph." Mixing the two metaphors in one whiteboard answer usually means the problem statement was misread.
Practice rows of different lengths
Build sorted lists of length 1, 2, 16, and 1024. Count probes for a hit near the middle and a miss above the max. Absent keys should still finish in about log2(n) steps, matching the 50 trace on the sixteen-value demo row [2].
When you explain the algorithm aloud, say what half you discard and why that half cannot contain the target. If you cannot say it in one sentence, the row is probably not sorted [2].
Hand learners the trace script first, then the arcade animation. Numbers in the trace make the halving story believable before the corridor graphics take over [1][2]. For a whiteboard, write the invariant "everything left of lo is too small; everything right of hi is too large" and keep it true after every assignment to lo or hi.
Browse Dev explainers for the full walk order.
Send this to the friend who binary-searches an unsorted list then blames Python.

Keep this guide
Filed under Dev explainers
Questions about this guide
How do I run binary search Python code for 21?
Run python3 binary_search.py 21 from the ALGO ARCADE folder.
Why does the binary search algorithm need sorted data?
Only an ordered row lets a middle value rule out an entire half.
Sources
- ALGO ARCADE READMEgithub.com
- ALGO ARCADE binary search sourcegithub.com