Skip to content

Commit fde9817

Browse files
committed
Binary search in python
1 parent a578d31 commit fde9817

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

python/15_bsearch/bsearch.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Author: Wenru
3+
"""
4+
5+
from typing import List
6+
7+
def bsearch(nums: List[int], target: int) -> int:
8+
"""Binary search of a target in a sorted array
9+
without duplicates. If such a target does not exist,
10+
return -1, othewise, return its index.
11+
"""
12+
low, high = 0, len(nums) - 1
13+
while low <= high:
14+
mid = low + (high - low) // 2
15+
if nums[mid] == target:
16+
return mid
17+
elif nums[mid] < target:
18+
low = mid + 1
19+
else:
20+
high = mid - 1
21+
22+
return -1

0 commit comments

Comments
 (0)