二分查找Python实现:
1、非递归方式
def bsearch(ls, value):
low, high = 0, len(ls)-1
while low <= high:
mid = low + (high - low) // 2
if ls[mid] == value:
return mid
elif ls[mid] < value:
low = mid + 1
else:
high = mid - 1
return -1
2、递归方式
def bsearch(ls, value):
return bsearch_recursively(ls, 0, len(ls)-1, value)
def bsearch_recursively(ls, low, high, value):
if low > high:
return -1
mid = low + (high - low) // 2
if ls[mid] == value:
return mid
elif ls[mid] < value:
return bsearch_recursively(ls, mid+1, high, value)
else:
return bsearch_recursively(ls, low, mid-1, value)
展开