Skip to content

Instantly share code, notes, and snippets.

@caseploeg
Created February 8, 2024 22:02
Show Gist options
  • Save caseploeg/da216f6a7a6f845df995542997dac894 to your computer and use it in GitHub Desktop.
Save caseploeg/da216f6a7a6f845df995542997dac894 to your computer and use it in GitHub Desktop.
binsearch()
#!/usr/bin/env python3
nums = sorted([int(x) for x in input().split()])
def search(x):
# low <= i < high
def binsearch(i, low, high):
if i == low or nums[i] == x:
return i
return binsearch((low + i)//2, low, i) if x <nums[i] else binsearch((i+high)//2, i, high)
i = binsearch(len(nums)//2, 0, len(nums))
return f'{x} found at index {i}' if nums[i] == x else f'{x} not found'
print(search(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment