一.顺序查找---O(n)
无序列表查找
def sequentialSearch(alist,item): pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos + 1 return found list = [2,3,1,4,5,6,0] print(sequentialSearch(list,5)) print(sequentialSearch(list,7))
有序列表查找
def ordersequentialSearch(alist,item): pos = 0 found = False stop = False while pos < len(alist) and not found and not stop: if alist[pos] == item: found = True else: if alist[pos] > item: stop = True else: pos = pos + 1 return found list = [1,2,3,4,5,6,7] print(ordersequentialSearch(list,3)) print(ordersequentialSearch(list,9))
二.二分查找---O(log^n)
def binarySearch(alist,item): first = 0 last = len(list) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: last = midpoint - 1 else: first = midpoint + 1 return found list = [0,1,2,3,4,5,6,7,8] print(binarySearch(list,3)) print(binarySearch(list,10))
递归实现二分查找
def binarySearchCur(alist,item): if len(alist) == 0: return False else: midpoint = len(alist) // 2 if alist[midpoint] == item: return True else: if item < alist[midpoint]: return binarySearchCur(alist[:midpoint],item) else: print(alist[midpoint+1:]) return binarySearchCur(alist[midpoint+1:],item)
def sequentialSearch(alist,item):pos = 0found = False
while pos < len(alist) and not found:if alist[pos] == item:found = Trueelse:pos = pos + 1return foundlist = [2,3,1,4,5,6,0]print(sequentialSearch(list,5))print(sequentialSearch(list,7))