R
R
Robin Alikhanov2020-01-17 12:02:42
Algorithms
Robin Alikhanov, 2020-01-17 12:02:42

Is this search binary?

# Бинарный поиск

def binary_search(list, item):
    low = 0 # начальная граница списка в которой осуществляется поиск
    high = len(list) - 1 # позиция последнего элемента списка

    while low <= high:# пока диапазон не сузится что они буду равны
        mid = (low + high) # проверяем средний элемент
        guess = list[mid]
        if item == guess:
            return mid
        if guess > item:
            high = mid - 1
        else:
            high = mid + 1
    return none

my_list = [1, 3, 5, 7, 9]

print(binary_search(my_list, 3)) # выводит порядковый номер наденного элемента

Indeed, in fact, in a binary search, an array or list is divided by two, or rather, the logarithm of a number from two is found.
that is, log2(8) = 3 That is, the logarithm of the number 8 from two is three and the binary search starts from the middle.
And in the code described above, the Mid number is reduced by one, that is, in fact, there is a normal search.
I don’t catch up why the code, as it were, performs a binary search, as it were

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2020-01-17
@robin1985

Binary if correct calculation errormid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question