二分查找递归实现 Python
This commit is contained in:
parent
615fbab083
commit
f90eb8f710
22
python/15_bsearch/bsearch_recursion.py
Normal file
22
python/15_bsearch/bsearch_recursion.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
"""
|
||||||
|
Author: dreamkong
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
def bsearch(nums: List[int], target: int) -> int:
|
||||||
|
return bsearch_internally(nums, 0, len(nums)-1, target)
|
||||||
|
|
||||||
|
|
||||||
|
def bsearch_internally(nums: List[int], low: int, high: int, target: int) -> int:
|
||||||
|
if low > high:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
mid = low+int((high-low) >> 2)
|
||||||
|
if nums[mid] == target:
|
||||||
|
return mid
|
||||||
|
elif nums[mid] < target:
|
||||||
|
return bsearch_internally(nums, mid+1, high, target)
|
||||||
|
else:
|
||||||
|
return bsearch_internally(nums, low, mid-1, target)
|
Loading…
Reference in New Issue
Block a user