编程实现:利用折半查找算法实现,在数据序列{1,6,8,16,36,66,88,100}中分别查找关键字8和56,找到后输出位序,找不到输出相应提示信息。
时间: 2023-10-04 15:05:03 浏览: 97
下面是利用折半查找算法实现的 Python 代码:
```python
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data = [1, 6, 8, 16, 36, 66, 88, 100]
key1 = 8
key2 = 56
pos1 = binary_search(data, key1)
if pos1 == -1:
print(f"{key1} not found in the list")
else:
print(f"{key1} found at position {pos1}")
pos2 = binary_search(data, key2)
if pos2 == -1:
print(f"{key2} not found in the list")
else:
print(f"{key2} found at position {pos2}")
```
输出结果为:
```
8 found at position 2
56 not found in the list
```
阅读全文