From fde9817fba095b5c0f8a4b512c0d8f8025ae42e5 Mon Sep 17 00:00:00 2001 From: Wenru Dong Date: Thu, 25 Oct 2018 20:41:01 +0100 Subject: [PATCH] Binary search in python --- python/15_bsearch/bsearch.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 python/15_bsearch/bsearch.py diff --git a/python/15_bsearch/bsearch.py b/python/15_bsearch/bsearch.py new file mode 100644 index 00000000..dc091b29 --- /dev/null +++ b/python/15_bsearch/bsearch.py @@ -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