Pythonic version of binary search

Premise: Ascending array, the element to be checked is in the array.

Binary search: is a recursive function c. The element to be checked a, the median b of the current array, if b=a, return the index of b, if b>a, call function c in the subarray on the left side of b, otherwise call function c in the subarray on the right side of b.

For the first time thinking, the result after programming according to the above ideas:

def binary_search(index, a, value):
    if a[(len(a) - 1) // 2] == value:
        return index + (len(a) - 1) // 2
    elif a[(len(a) - 1) // 2] < value:
        return binary_search(index + (len(a) - 1) // 2 + 1, a[(len(a) - 1) // 2 + 1:], value)
    else:
        return binary_search(index, a[0:(len(a) - 1) // 2 + 1], value)

The second thought, simplify the median calculation logic:

def binary_search(index, a, value):
    if a[len(a) // 2] == value:
        return index + len(a) // 2
    elif a[len(a) // 2] < value:
        return binary_search(index + len(a) // 2, a[len(a) // 2:], value)
    else:
        return binary_search(index, a[0:len(a) // 2], value)

The third thought, remove the return functional syntax and change it to the lambda expression form:

binary_search = lambda index,a,value: index + len(a) // 2 if a[len(a) // 2] == value else binary_search(index + len(a) // 2, a[len(a) // 2:], value) if a[len(a) // 2] < value else binary_search(index, a[0:len(a) // 2], value)

The above is the process of turning binary search into "one-line version".

Run the test:

if __name__ == '__main__':
    a = [1, 2, 33, 43, 52, 66, 88, 99, 111, 120]
    print(f"Target index: {binary_search(0, a, value=33)}")

The result is as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647421&siteId=291194637