Grokking algorithms (Chapter 1)

dichotomy

The input of the dichotomy is a sorted list, and the position of the number to be searched, and the output is the position of the number to be searched. If there is no such number, null is returned.

The O mark always corresponds log_{2}.

For a list with a length of 8, using simple search, the worst need to search 8 times, and using the dichotomy search, then only need to search at most 3 times ( log_{2}8=3)

The following is the python version of the dichotomy code

def binary_search(list,item):
    low = 0
    high = len(list)-1
    while low<=high:
        middle = (low+high)/2
        if list[middle] = item:
            return middle
        else if list[middle]<item:
            low = middle+1
        else if:
            high = middle -1
        else:
            return None

Linear time (simple search): To process a list of 100 elements, at most 100 operations are required

log time (binary search): To process a list of 100 elements, at mostlog_{2}100=7 operations are required

Big O mark

O notation used to represent a large number of operating (time and does not matter) , such as arrays of n elements, using simple search, search is required n times, then referred to as O (n), using the bisection method, the same process array , Then it is O( log_{2}n), which can also be written as O( calm).

Comparison of the efficiency of major O signs, the horizontal axis is the number of operations, and the vertical axis is the running time

Final summary 

Guess you like

Origin blog.csdn.net/Gussss/article/details/95185257