Answer the question
In order to leave comments, you need to log in
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
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.
Your implementation will loop if there is no such element in the list.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question