本文用python3实现了二分查找算法,分别使用递归方法和非递归方法。
(一)递归实现
def binarySearch(s, k):
return binarySearch_c(s, 0, len(s) - 1, k)
def binarySearch_c(s, low, high, k):
if low > high:
return -1
mid = low + (high - low) // 2
if s[mid] == k:
return mid
elif s[mid] > k:
return binarySearch_c(s, low, mid - 1, k)
else:
return binarySearch_c(s, mid + 1, high, k)
for _ in range(int(input())):
s = list(map(int, input().split()))
k = int(input())
print(binarySearch(s, k))
(二)非递归实现
def binarySearch(s, k):
low = 0
high = len(s) - 1
while low <= high:
mid = low + (high - low) // 2
if s[mid] == k:
return mid
elif s[mid] > k:
high = mid - 1
else:
low = mid + 1
return -1
for _ in range(int(input())):
s = list(map(int, input().split()))
k = int(input())
print(binarySearch(s, k))
三个易错的关注点:
1、循环退出条件:
low<=high,而不是low<high
2、mid的取值:
mid = (low + high) // 2 这种写法可能造成溢出
mid = low + (high - low) // 2 正确写法
mid = low + ((high - low) >> 1 位运算性能更优
3、low和high的更新:
low = mid + 1
high = mid - 1
最后,二分查找要基于顺序表结构,并且是有序数组,其时间复杂度为O( log (n) )。
来源:CSDN
作者:-TOXNO-
链接:https://blog.csdn.net/qq_36911138/article/details/104146641