Skip to content

Commit

Permalink
Merge pull request wangzheng0822#107 from jerryderry/bsearch-python
Browse files Browse the repository at this point in the history
Binary search in python
  • Loading branch information
wangzheng0822 authored Oct 26, 2018
2 parents 484524e + fde9817 commit 771fe9c
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 771fe9c

Please sign in to comment.