用python写顺序查找和折半查找
时间: 2024-05-14 22:17:44 浏览: 78
顺序查找和折半查找
顺序查找(线性查找):
```python
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
```
折半查找(二分查找):
```python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
```
阅读全文