1. What is binary search:
- 1. Starting from the middle element of the array, the search process ends if the intermediate element is exactly the element to be found;
- 2. If a particular element is greater than or less than the middle element, it is found in the half of the array greater than or less than the middle element, and is compared with the beginning from the middle element.
- 3. If an array of steps is empty, the representation cannot be found.
I halve each time to find, its time consumption is O (Logn)
One of the simplest loop algorithms is:
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
There is also a classification algorithm:
defbinary_search_recursion (lst,value):defchild_recursion (lst,value,low,high):ifhigh<Low :returnNone Mid= (Low+high)//2ifLst[mid]>Value:returnChild_recursion (lst,value,low,mid-1) eliflst[mid]<Value:returnChild_recursion (lst,value,mid+1, High)Else: returnMidreturnChild_recursion (Lst,value,0,len (LST)-1)
Test performance;
if __name__=="__main__": ImportRandom LST=[random.randint (0,10000) for_inchRange (10000)] Lst.sort ()deftest_recursion (): Binary_search_recursion (LST,999) defTest_loop (): Binary_search_loop (LST,999) ImportTimeit 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 algorithm: Dichotomy lookup (1)