1.顺序查找(线性查找)
时间复杂度O(n)
def linear_search(ls,value):
for ind val in enumerate(ls):
if val==value:
return ind
else:
return None
2.二分查找
时间复杂度O(logn)
def binary_search(ls,value):
left=0
right=len(ls)-1
while left<=right:
mid=(left+right)//2
if ls[mid]==value: #刚好等于
return mid
elif ls[mid]<value: #value在ls[mid]右边
left=mid+1
elif ls[mid]>value: #value在ls[mid]左边
right=mid-1
else:
return None