Python algorithm: Dichotomy lookup (1)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.