1. 程式人生 > >二分法——Python實現

二分法——Python實現

def dichotomy(list1,target):
    length = len(list1)
    index_low = 0
    index_high = length - 1

    while index_low <= index_high:
        index_midle = int((index_low + index_high) / 2)
        guess = list1[index_midle]
        if guess == target:
            return index_midle
        elif guess > target:
            index_high = index_midle - 1
        elif guess < target:
            index_low = index_midle + 1
    return None

    
list_1 = [1,2,3,4,5,6,7,8,9]
target_1 =3
print(dichotomy(list_1,target_1))