S
S
slmuim2021-08-29 21:06:41
Python
slmuim, 2021-08-29 21:06:41

Is this the correct implementation of binary search?

Hello! I started learning algorithms, I tried to write a binary search in Python, but I don’t understand if it works correctly. By time, it works the same as a regular search.

def binary_search(n, lst):
    guess = 0
    while guess != n:
        mid = int(len(lst)/2)
        if lst[mid] == n:
            guess = lst[mid]
            return guess
        elif lst[mid] < n:
            lst = lst[mid:]
        else:
            lst = lst[:mid]

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
Wataru, 2021-08-29
@slmuim

Works slowly because you are truncating the input array every time. To do this, you have to bypass and copy the entire necessary part. Therefore, the total running time will be O(n).
In order to work quickly, you should not change lst, but remember the indexes of the boundaries of the current piece.
Also, you need to stop when the piece in question becomes empty so that the solution does not crash if the desired number is not in the list.
Lastly, Python has an integer division operator, //. Use it instead of casting to int after division.

V
Vindicar, 2021-08-29
@Vindicar

Your implementation will loop if there is no such element in the list.

G
GavriKos, 2021-08-29
@GavriKos

Without going into the search logic:
- what happens if lst does not contain the required element?
- what does the method actually return?
UPD:
- what if I need to find 0 in the array? ;-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question