使用二分查找法需要查找3次。
python程序如下:
def binary_search(arr, x):
left =0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
left = mid + 1
else:
right = mid - 1
return -1
arr = [98, 88, 76, 65, 48, 24, 12, 12, 8, 1]
x = 8
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")