Binary Search Interactive Laboratory

O(log n) Engine
Keyboard: [Space] Play/Pause [→] Step [R] Reset
Array Search Space Ready to Search
Select a target and click Next › or ▶ Play to trace logarithmic halving.
Synchronized Execution Trace Python
1: def binary_search(arr, target):
2: low, high = 0, len(arr) - 1
3: while low <= high:
4: mid = (low + high) // 2
5: if arr[mid] == target: return mid
6: elif arr[mid] < target: low = mid + 1
7: else: high = mid - 1
8: return -1 # Not found
State Inspector & Race Metrics Step 0/0
Low Index (L)
-
High Index (R)
-
Mid Index (M)
-
arr[mid] vs Target
-
Binary Search: 0 comparisons Max Worst Case: 0
Linear Search Comparison: 0 checks Efficiency: 1.0x

Why sorted order lets binary search discard an interval

Read the explanation

Binary search needs the values in sorted order. The page sorts its randomly generated unique values before searching. Consider this illustrative sorted nine element array and target twenty eight. Low begins at index zero and high at eight. Taking the floor of their average selects index four, whose value is twenty. Because twenty is smaller than the target, every value through index four can be discarded. Sorted order makes that deduction valid. The surviving indices are five through eight. Their midpoint is floor of thirteen divided by two, which is six. The value at index six is twenty eight, so the search stops after two comparisons. Seven would be the count for a linear search starting at the left. The animation also shows initialization and bound updates as separate frames. Those frames are not additional midpoint comparisons. An unsuccessful search ends when low crosses high. The page can generate a missing target above the largest value, allowing you to inspect that boundary. Its displayed bound for nine values is ceiling of log base two of ten, which is four comparisons. Preset names still need to be checked against the actual trace: with sixteen values, Best Mid selects index eight, but the first lower midpoint is index seven. That preset therefore takes four comparisons in this implementation, not one.

Super generates helpful tools and automates fact-checking across the internet proactively. If you enjoyed this tool, build your own with Super and share it with a friend.