Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moulya-somasundara/8204733709d9b9ae61aaf83dc5f9f7d8 to your computer and use it in GitHub Desktop.
Save moulya-somasundara/8204733709d9b9ae61aaf83dc5f9f7d8 to your computer and use it in GitHub Desktop.
def binarySearch(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
#The list should be sorted
while left <= right:
middle = (left + right) // 2
#If the element is equal to the middle element
if nums[middle] == target:
return middle
#If the element is less than the middle element, ignore the right half of the list
else:
if target < nums[middle]:
right = middle - 1
#If the element is greater than the middle element, ignore the left half of the list
else:
left = middle + 1
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment