Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created January 6, 2026 12:17
Show Gist options
  • Select an option

  • Save pythonhacker/3de90f0478abf0e2bbedf076e3e88e72 to your computer and use it in GitHub Desktop.

Select an option

Save pythonhacker/3de90f0478abf0e2bbedf076e3e88e72 to your computer and use it in GitHub Desktop.
Binary search using bisect module
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