Data structure and algorithm python to achieve linear search, binary search

Linear search: find the end from the beginning, and return it when we find what we want
Binary search: get the middle value of an array, if the data to be checked is larger than the middle value, the subscript is +1, otherwise the subscript is -1

#二分查找
def binary_search(sorked_array,val):
    if not sorked_array:
        return  -1
    beg = 0
    end = len(sorked_array) -1
    while beg <= end:
        mid = int((end+beg) / 2)
        if sorked_array[mid] == val:
            return mid
        elif sorked_array[mid] > val:
            end = mid - 1
        else:
            beg = mid + 1
    return  -1

Guess you like

Origin blog.csdn.net/weixin_44865158/article/details/100797243