C
C
Cyril2020-07-12 14:04:53
Python
Cyril, 2020-07-12 14:04:53

How does the code from the book "Groaming Algorithms" work?

Hello!
I started reading the book "Groaming Algorithms" and in the first example I can't understand how one of the lines works.
The code itself:

def binary_search(list, item):
    low = 0
    high = len(list)-1

    while low <= high:
        mid = (low + high)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None


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

print(binary_search(my_list, 3))
print(binary_search(my_list, -1))


I can't understand why in this line:

guess = list[mid]

guess = 9 ?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
ScriptKiddo, 2020-07-12
@Pus1st

In the first iteration

low = 0
high  = 4

0+4 = 4
Python indexes start at zero, so the element at index 4 is the fifth element in the array [1, 3, 5, 7, 9]

S
Sergey Gornostaev, 2020-07-12
@sergey-gornostaev

First you need to learn the language, and only then take on the algorithms.

D
Denis Zagaevsky, 2020-07-12
@zagayevskiy

Because mid = (low + high)
We need to divide by two more.

D
Developer, 2020-07-12
@samodum

Do you understand that there is a cycle? And every iteration guess will be different

O
Olga Pavlova, 2022-01-26
@pavloops

def binary_search ( list, item) :
    # в low и high хранятся границы части списка, где выполняется поиск
    low = 0
    high = len(list)-1
    i = 0
  # Пока не останется один элемент
    while low <= high:
        # Проверяем средний элемент
        mid = (low + high)//2
        guess = list[mid]
        # Значение найдено
        if guess == item:
            return mid
        # Значение велико
        if guess > item:
            high = mid - 1
        # Значение мало
        else:
            low = mid + 1
    # Значение не найдено
    return None

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question