I wrote a binary search algorithm and tried running it on different editors, i.e pycharm, github, jupiter notebook. And all of them are not showing any output. Is there something wrong with my code?
def b_search(num):
numlist = [12, 23, 34, 54, 67, 81, 99, 102]
s = 0
e = len(numlist) - 1
m = round((s+e)/2)
n = 1
found = False
while (found == False) or ( n != 0):
if num == numlist[m]
found = True
elif num > numlist[m]:
if m ==s or m==e:
n=0
else:
s = round(m+1)
m = round((s+e)/2)
elif num < numlist[m]:
if m==s or m==e:
n=0
else:
e = round(m-1)
m = round((s+e)/2)
if n=0:
return -1
else:
return m
print(b_search(23))
I am keen to find any problems in logic or syntax.
You shouln't rounded the s and e, you are dealing with only integers, so thats not necessary.
Fixed the identation and logic errors
Altough you don't want it to be optimised, when I fixed your code it always return -1.
Added a check to see if the search range is exhausted (s becomes greater than e). If this happens, it means the target number is not in the list, and we set n to 0 to exit the loop.
Moved the calculation of m inside the loop to update the middle index correctly.
Added colons at the end of the if num == numlist[m] and if num > numlist[m] lines to correct the syntax.
Changed if n=0: to if n == 0: to correct the syntax for comparison. (as Sembei Norimaki pointed out)
Changed while (found == False) or (n != 0): to while (found == False) and (n != 0): to ensure that the loop continues only if both conditions are true.If n = 0 we want to exit the loop, and if we find the number we also want do exit.
def b_search(num):
numlist = [12, 23, 34, 54, 67, 81, 99, 102]
s = 0
e = len(numlist) - 1
n = 1
found = False
while (found == False) and (n != 0):
m = round((s + e) / 2)
if num == numlist[m]:
found = True
elif num > numlist[m]:
s = m + 1 # Update s directly without rounding
else: # num < numlist[m] (if it isn't >, certainly is =<)
e = m - 1 # Update e directly without rounding
if s > e: # Check if the search range is exhausted
n = 0
if n == 0:
return -1
else:
return m
print(b_search(23)) #outputs 1
print(b_search(99)) #outputs 6
print(b_search(100)) #outputs -1
print(b_search(12)) #outputs 0
print(b_search(102)) #outputs 7
print(b_search(54)) #outputs 3
print(b_search(81)) #outputs 5