Python algorithm-binary search algorithm

Algorithm (Algorithm)

Algorithm refers to the accurate and complete description of the problem-solving scheme. It is a series of clear instructions to solve the problem. The instruction in the algorithm describes a calculation that can be input from an initial state and (possibly empty) when it runs. At the beginning, after a series of limited and clearly defined states, finally produce output and stop at a final state. The
algorithm is also an indispensable part of our python. Today we will learn about the binary search algorithm in python.

Binary search

In our daily life, if I want to find an element in a list, what methods do we have? We can compare the search one by one. If there are 100 elements, we have to spend 100 units of time, which is more wasteful Time, just like when we look up someone’s phone number in the phone book, we have to search page by page, which is time-consuming and laborious. Is there a more labor-saving way? Binary search is a good choice.
Binary search is an algorithm. , Its input is an ordered list of elements (must be ordered) , if the element to be searched is contained in the list, the binary search returns its position; otherwise it returns null. The binary_search function accepts an ordered array and elements. If specified If the element is in this array, its position is returned.
Just like the game we usually play: to
guess a number between 1 and 100, we have two methods:
1. Start with 1, then 2, 3, 4, 5... know The number we want to guess, if the number is 1, it's okay to say that we succeeded once, but if the number is 100, we have to guess 100 times
2. Let's guess a middle number (50), and then come Judge whether this number is larger or smaller than 50. If it is larger than 50, the next time it will be guessed within 51 to 100. If it is smaller than 50, the next time it will be guessed within 1 to 49, so that the range of our guess will be Keep getting smaller and smaller until the guess is right. In this way, we only need to guess 7 times at most to get the correct answer. This is a binary search.

def binary_search(list, item):  # 其输入的是一个列表和查找的元素
    a = 0   # 数字在0~列表的长度之间
    b = len(list) - 1
    while a <= b:   # 判断列表之中是否存在数字
        find_num = (a + b)      # 找到列表中间的那个数字
        num = list[find_num]
        if num == item:     # 判断查找的元素是否就是列表中间的数字
            return find_num     # 若是则返回中间的那个数字
        elif num > item:        # 若中间的那个数字大于查找的数字
            b = find_num - 1        # 则将查找范围的尾减半
        else:                   # 若中间的那个数字小于查找的数字
            a = find_num + 1        # 则将查找范围的首减半
    return None


my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 5))        # 结果为2
print(binary_search(my_list, -5))       # 结果为None

Guess you like

Origin blog.csdn.net/Layfolk_XK/article/details/108198743