python的算法:二分法查找(1)
阿新 • • 發佈:2017-07-04
port == 歸類 算法 開始 log spa loop __name__
1.什麽是二分法查找:
- 1.從數組的中間元素開始,如果中間元素正好是要查找的元素,則搜素過程結束;
- 2.如果某一特定元素大於或者小於中間元素,則在數組大於或小於中間元素的那一半中查找,而且跟開始一樣從中間元素開始比較。
- 3.如果在某一步驟數組為空,則代表找不到。
每次都是i減半查找,其時間消耗為O(logn)
最簡單的一個循環算法就是:
def binary_search_loop(lst,value): low,high=0,len(value)-1 while low<=high: mid=(low+high)//2 if lst[mid]<value: low=mid+1 elif lst[mid]>value: high=mid-1 else: return mid return None
還有一個第歸類算法:
def binary_search_recursion(lst,value): def child_recursion(lst,value,low,high): if high<low: return None mid=(low+high)//2 iflst[mid]>value: return child_recursion(lst,value,low,mid-1) elif lst[mid]<value: return child_recursion(lst,value,mid+1,high) else: return mid return child_recursion(lst,value,0,len(lst)-1)
測試一下性能;
if __name__=="__main__": importrandom lst=[random.randint(0,10000) for _ in range(10000)] lst.sort() def test_recursion(): binary_search_recursion(lst,999) def test_loop(): binary_search_loop(lst,999) import timeit t1=timeit.Timer("test_recursion()",setup="from __main__ import test_recursion") t2 = timeit.Timer("test_loop()", setup="from __main__ import test_loop") print("recursion:",t1.timeit()) print("loop:", t2.timeit())
python的算法:二分法查找(1)