+ 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")

28th Jun 2022, 9:27 PM
Mohammad Shadman Khan
Mohammad Shadman Khan - avatar
5 Antworten
+ 2
Edward Finkelstein why my code didn't work?
29th Jun 2022, 8:50 AM
Mohammad Shadman Khan
Mohammad Shadman Khan - avatar
+ 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
29th Jun 2022, 9:37 AM
Edward Finkelstein
Edward Finkelstein - avatar
+ 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")
28th Jun 2022, 10:08 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 1
Edward Finkelstein I don't want to use flag
29th Jun 2022, 8:09 AM
Mohammad Shadman Khan
Mohammad Shadman Khan - avatar
+ 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
29th Jun 2022, 8:44 AM
Edward Finkelstein
Edward Finkelstein - avatar