Algorithms · Visualized
Binary Search
Searching Algorithms
Six search strategies on a sorted array — from the obvious linear scan to log-time binary search and beyond.
Binary Search finds a target in a sorted array by repeatedly checking the middle element and eliminating half of the remaining elements each time — like guessing a number between 1 and 100 by always guessing the midpoint and narrowing down 'higher' or 'lower'. Time: O(log n) average, O(log n) worst; space: O(1) iterative, O(log n) recursive (call stack).
Big-O: Binary O(log n), Linear O(n), Jump O(√n), Interpolation O(log log n) avg, Exponential O(log n).
Binary Search
SearchingBinary Search finds a target in a sorted array by repeatedly checking the middle element and eliminating half of the remaining elements each time — like guessing a number between 1 and 100 by always guessing the midpoint and narrowing down 'higher' or 'lower'.
How Binary Search Works
- Set two pointers, 'low' at the start and 'high' at the end of the array.
- Calculate the middle index: mid = (low + high) / 2.
- If the middle element equals the target, you're done — return its index.
- If the middle element is smaller than the target, the target must be in the right half, so move 'low' to mid + 1.
- If the middle element is bigger than the target, the target must be in the left half, so move 'high' to mid - 1.
- Repeat until 'low' exceeds 'high' (target not found) or you find a match.
Binary Search Worked Example
Input: {array: [1, 3, 5, 7, 9, 11, 13], target: 11}
low=0, high=6, mid=3 (value 7). 7<11 → search right half, low=4. mid=(4+6)/2=5 (value 11). Match! Return index 5. Took just 2 comparisons instead of checking all 7 elements.
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Binary Search Time & Space Complexity
When to Use Binary Search
- Searching large sorted datasets extremely fast — e.g. looking up a word in a sorted dictionary.
- Foundation for many other algorithms: finding boundaries, rotated array search, 'search space' problems like Koko Eating Bananas.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.