Skip to content

Commit

Permalink
Binary search in python
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryderry committed Oct 25, 2018
1 parent a578d31 commit fde9817
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions python/15_bsearch/bsearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
Author: Wenru
"""

from typing import List

def bsearch(nums: List[int], target: int) -> int:
"""Binary search of a target in a sorted array
without duplicates. If such a target does not exist,
return -1, othewise, return its index.
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1

return -1

0 comments on commit fde9817

Please sign in to comment.