Last active
April 3, 2020 14:05
-
-
Save opethe1st/10a57e593444888f7cc6a440631cd19d to your computer and use it in GitHub Desktop.
Binary Search! - How would you write binary search?
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
found a bug in this.. haha