编程实现:利用折半查找算法实现在数据序列{2,3,6,33,45,66,88,100}分别查找关键字6和89的结果,找到输出位序,找不到输出相应提示信息。
时间: 2023-06-26 19:07:05 浏览: 62
好的,以下是 Python 代码实现折半查找算法:
```python
def binary_search(array, target):
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) // 2
if array[mid] < target:
left = mid + 1
elif array[mid] > target:
right = mid - 1
else:
return mid
return -1
data = [2,3,6,33,45,66,88,100]
target1 = 6
target2 = 89
result1 = binary_search(data, target1)
if result1 == -1:
print(f"{target1} not found in data.")
else:
print(f"{target1} found at index {result1} in data.")
result2 = binary_search(data, target2)
if result2 == -1:
print(f"{target2} not found in data.")
else:
print(f"{target2} found at index {result2} in data.")
```
输出结果为:
```
6 found at index 2 in data.
89 not found in data.
```
所以,关键字6的位置为2,关键字89在数据中未找到。
阅读全文