Last active
April 1, 2020 10:22
-
-
Save nhudinhtuan/402e7d5eb110fafc0e870bd62dd99195 to your computer and use it in GitHub Desktop.
Binary search - find the first position
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 find_first_pos(arr, target): | |
left = 0 | |
right = len(arr) - 1 | |
first_position = -1 # keep track of the latest valid mid position | |
while left <= right: | |
mid = left + (right - left) // 2 | |
if arr[mid] == target: | |
first_position = mid | |
right = mid - 1 # continue searching to the left | |
elif arr[mid] < target: | |
left = mid + 1 | |
else: | |
right = mid - 1 | |
return first_position |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment