-
Notifications
You must be signed in to change notification settings - Fork 0
/
bsearch.py
44 lines (37 loc) · 1014 Bytes
/
bsearch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# -*- coding: utf-8 -*-
from typing import List
def bsearch_base(nums, target):
"""
:param nums: 待查找数列
:param target: 查找目标
:return: 查找结果
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low)//2
if nums[mid] == target:
return nums[mid]
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return "Not Found"
def bsearch(nums: List, target: int) -> int:
"""
:param nums: 待查找数列
:param target: 查找目标
:return: 查找结果
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low)//2
if nums[mid] == target:
return nums[mid]
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
if __name__ == '__main__':
a = [1, 2, 3, 7, 10, 23]
print(bsearch(a, 7))