Created
January 6, 2026 12:17
-
-
Save pythonhacker/3de90f0478abf0e2bbedf076e3e88e72 to your computer and use it in GitHub Desktop.
Binary search using bisect module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import bisect | |
| def binary_search(a, x, lo=0, hi=None): | |
| """ Search for item x in a using bisect binary search """ | |
| if hi is None: | |
| hi = len(a) | |
| pos = bisect.bisect_left(a, x, lo, hi) | |
| if pos != hi and a[pos] == x: | |
| return pos | |
| # You may raise an exception instead | |
| return -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment