Skip to content

Commit c1896d5

Browse files
committed
add binary search
1 parent d09592e commit c1896d5

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/binary_search.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def search(self, nums: List[int], target: int) -> int:
6+
left, right = 0, len(nums) - 1
7+
while left <= right:
8+
middle = (left + right) // 2
9+
if nums[middle] > target:
10+
right = middle - 1
11+
elif nums[middle] < target:
12+
left = middle + 1
13+
else:
14+
return middle
15+
return -1

tests/test_binary_search.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from binary_search import Solution
2+
3+
testcase = [{"testcase": [-1, 0, 3, 5, 9, 12], "target": 9, "result": 4}]
4+
5+
6+
def test_binary_search():
7+
for tc in testcase:
8+
nums = tc["testcase"]
9+
target = tc["target"]
10+
ans = Solution().search(nums, target)
11+
assert ans == tc["result"]

0 commit comments

Comments
 (0)