Python implements binary search algorithm (binary search)

1. Principle

Binary search , also known as binary search , the advantage of a small number of comparisons, fast find speed, average performance; drawback is the requirement to be ordered lookup table, and insert delete difficulties. Therefore, the binary search method is suitable for searching frequently ordered lists that do not change frequently. First of all, suppose the elements in the table are arranged in ascending order. Compare the key in the middle position of the table with the search key. If the two are equal, the search is successful; otherwise, use the middle position record to divide the table into two sub-tables, if The key of the middle position record is greater than the search key, then the previous sub-table is further searched, otherwise the latter sub-table is further searched. Repeat the above process until a record that meets the conditions is found, and the search is successful, or until the sub-table does not exist, the search is unsuccessful at this time.
Insert picture description here

2. Applicable conditions

Binary search is conditional. First, it is ordered. Secondly, because the binary search operation is subscript, the requirement is order.
Optimal time complexity : O(1)
Worst time complexity : O(logn)

Code

"""
1. 二分查找是有条件的,首先是有序,其次因为二分查找操作的是下标,所以要求是顺序表
2. 最优时间复杂度:O(1)
3. 最坏时间复杂度:O(logn)
"""

# def binary_chop(alist, data):
#     """
#     递归解决二分查找
#     :param alist:
#     :return:
#     """
#     n = len(alist)
#     if n < 1:
#         return False
#     mid = n // 2
#     if alist[mid] > data:
#         return binary_chop(alist[0:mid], data)
#     elif alist[mid] < data:
#         return binary_chop(alist[mid+1:], data)
#     else:
#         return True

def binary_chop(alist, data):
    """
    非递归解决二分查找
    :param alist:
    :return:
    """
    n = len(alist)
    first = 0
    last = n - 1
    while first <= last:
        mid = (last + first) // 2
        if alist[mid] > data:
            last = mid - 1
        elif alist[mid] < data:
            first = mid + 1
        else:
            return True
    return False

if __name__ == '__main__':
    lis = [2,4, 5, 12, 14, 23]
    if binary_chop(lis, 14):
        print('查找成功!')

Guess you like

Origin blog.csdn.net/yjh_SE007/article/details/105717000