+ 2
Need help with this code for binary search in python. Please tell me what's wrong in this?
arr = [1,2,3,4,5] n = int(input()) L = 0 H = (len(arr) - 1) while L <= H: M = (H+L)//2 if arr[M] == n: print("Found") elif arr[M] < n: L = M+1 elif arr[M] > n: H = M-1 else: print("Not Found")
5 Réponses
+ 2
Edward Finkelstein why my code didn't work?
+ 2
Because in the if-statement, you need a break or else you get an infinite loop. And the else does not correctly test for it it is not found. Actually, there is a bug in the code I just posted, it is better to check if a max number of iterations, which for binary search is given as log2(len(arr)).
arr = [1,2,3,4,5]
n = int(input())
L, count = 0, 0
H = (len(arr) - 1)
while L <= H:
M = (H+L)//2
if arr[M] == n:
print("Found")
break
elif len(arr) <= 2**count:
print("Not found")
break
elif arr[M] < n:
L = M+1
elif arr[M] > n:
H = M
count+=1
+ 1
Better?
arr = [1,2,3,4,5]
n = int(input())
L = 0
H = (len(arr) - 1)
flag=False
while L <= H:
M = (H+L)//2
if arr[M] == n:
flag=True
break
elif arr[M] < n:
L = M+1
elif arr[M] > n:
H = M-1
print("found") if flag else print("not found")
+ 1
Edward Finkelstein I don't want to use flag
+ 1
Ok, then this maybe?
arr = [1,2,3,4,5]
n = int(input())
L = 0
H = (len(arr) - 1)
while L <= H:
M = (H+L)//2
if arr[M] == n:
print("Found")
break
elif arr[M] < n:
if M==len(arr)-1:
print(n,"Not found")
break
L = M+1
elif arr[M] > n:
if M==0:
print(n,"Not found")
break
H = M-1