列表查找:从列表中查找指定元素
- 输入:列表、待查找元素
- 输出:元素下标或未查找到元素
list1=[1,3,4,5,6,8,9,12,15,20] print(list1.index(8))
def listSearch(list,num): i=0 while i<len(list)-1: if list[i]==num: return i else: i=i+1 return None
二分查找
二分查找的前提是列表是有序的
def search(arr,num): low=0 high=len(arr)-1 while low <= high: mid=(low+high)//2 if arr[mid]>num: high=mid-1 elif arr[mid]<num: low=mid+1 else: return mid return None list1=[1,3,4,5,6,8,9,12,15,20] print(search(list1, 8))
递归版二分查找:
def bin_serach_rec(li,val,low,high): if low<=high: mid = (low+high)//2 if li[mid] >val: return bin_serach_rec(li,val,low,mid-1,) elif li[mid]<val: return bin_serach_rec(li,val,mid+1,high) else: return mid else: return li = list(range(0,101,2)) print(serach(li,98))