Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Created April 1, 2020 10:22
Show Gist options
  • Save nhudinhtuan/8664912981e760dc24c611d19ebdff0a to your computer and use it in GitHub Desktop.
Save nhudinhtuan/8664912981e760dc24c611d19ebdff0a to your computer and use it in GitHub Desktop.
Binary search - find the last position
def find_last_pos(arr, target):
left = 0
right = len(arr) - 1
last_position = -1 # keep track of the latest valid mid position
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
last_position = mid
left = mid + 1 # continue searching to the right
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return last_position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment