Skip to content

Instantly share code, notes, and snippets.

@opethe1st
Last active April 3, 2020 14:05
Show Gist options
  • Save opethe1st/10a57e593444888f7cc6a440631cd19d to your computer and use it in GitHub Desktop.
Save opethe1st/10a57e593444888f7cc6a440631cd19d to your computer and use it in GitHub Desktop.
Binary Search! - How would you write binary search?
def partition(nums, condition):
"""
nums is ordered so that all the cases where condition is false at the beginning and it is true towards the end.
We are tryng to find the first index where the condition is true.
e.g
nums = [1, 1, 1, 1, 2]
condition = lambda val: val < 2
partition will return 4
"""
start = 0
span = len(nums)
while span:
new_span = span>>1
if start+new_span < len(nums) and not condition(nums[start+new_span]):
start = start + (span - new_span)
span = new_span
return start
def bisect_left(nums, target):
condition = lambda x < target
return partition(nums, condition)
def bisect_right(nums, target):
condition = lambda x <= target
return partition(nums, condition)
def binary_search(nums, target):
index = bisect_left(nums, target)
if index < len(nums) and nums[index]==target:
return index
return -1
@opethe1st
Copy link
Author

found a bug in this.. haha

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment