搜索算法:
1.线性搜索:循环遍历,判断是否等于目标值
2.二分法:(需要有序)先定一个起点和终点left,right,当left<right时,取中间值mid,如果目标值小于mid,则right=mid-1,反之亦然
# 线性搜索
def action1(arr, target):
for i in arr:
if i == target:
print(arr.index(i))
# 二分法
def action2(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
print(mid)
break
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
if __name__ == '__main__':
arr = 'adsyui'
target = 'y'
# 线性搜索
action1(arr, target)
arr = [1, 3, 4, 7, 9]
target = 4
# 二分法
action2(arr, target)