搜索,顾名思义就是在一个序列中找出某个元素。
二分查找
二分查找只能作用于有序的顺序表中。
def binary_search(alist, item): """二分查找,递归版""" n = len(alist) if n > 0: mid = n//2 if alist[mid] == item: return True elif item < alist[mid]: return binary_search(alist[:mid],item) else: return binary_search(alist[mid+1:],item) return False if __name__ == '__main__': li = [17,20,26,44,45] print(binary_search(li,45)) print(binary_search(li, 55))
def binary_search(alist, item): """二分查找,非递归""" n = len(alist) first = 0 last = n-1 while first<=last: mid = (first+last)//2 if alist[mid] == item: return True elif item<alist[mid]: last = mid-1 else: first = mid + 1 return False
二分查找时间复杂度是O(logn)