Binary search bisection in Python
Codemia Knowledge Hub ·
Understanding Binary Search (Bisection) in Python
Binary search, also known as the bisection method, is a fundamental algorithm used to find the position of a target value within a sorted array. It operates by repeatedly dividing the array in half and eliminates one half from consideration until the target value is found. This makes it a powerful and efficient search mechanism with a time complexity of .
How Binary Search Works
Binary search operates under two critical assumptions:
- Array must be sorted: Binary search can only be applied to data structures that are sorted.
- Divide and conquer: By selecting the middle element as the pivot, the algorithm determines if the target lies to the left or right of the pivot, effectively halving the search space.
Algorithm Steps
- Initialize two pointers, `left` and `right`, representing the bounds of the array.
- Calculate the middle index: `mid = left + (right - left) // 2`.
- Compare the middle element of the array with the target:
- If equal, return the middle index.
- If the target is less than the middle element, adjust the `right` pointer to `mid - 1`.
- If the target is greater, adjust the `left` pointer to `mid + 1`.
- Repeat steps 2-3 until the `left` pointer exceeds the `right` pointer.
- If the target isn't found, return a value indicating failure (commonly `-1`).
Python Implementation
Here's a simple implementation of binary search in Python:
- Efficiency: With its logarithmic time complexity, binary search is significantly faster than linear search techniques.
- Scalability: Works well with large datasets.
- Lower Bound Binary Search: Used to find the smallest index at which a given element can be inserted.
- Upper Bound Binary Search: Finds the largest index at which a given element can be inserted.
- Introduction to Algorithms, Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C.
- The Algorithm Design Manual, Skiena, S.
Related reading
- Binary Search in 2D Array
- Binary Search Problems?
- Binary Search Terminating Condition
- Binary search to find the rotation point in a rotated sorted list
- Binning a column with pandas
- bisect.insort complexity not as expected
- Binary Search using start end vs. using start end
- Binary search vs binary search tree
Course lessons on this
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.