+ 1

please find bug in binary search algo

elem = [11,23,8,14,30,9,6,17,22,28,25,15,7,10,19] arr = sorted(elem) def binary_search(tgt): start = 0 end = len(arr)-1 while (start < end): mid = int((start+end)/2) if tgt == arr[mid]: print("At index location ", mid) break else: if tgt < arr[mid]: end = mid - 1 else: start = mid + 1 binary_search(30) #my program not finding some numbers like as: 6,8,10,14,17,22,25,30

21st Apr 2019, 12:34 PM
Aakash Gupta
Aakash Gupta - avatar
3 odpowiedzi
+ 1
Thanks
22nd Apr 2019, 5:00 AM
Aakash Gupta
Aakash Gupta - avatar
0
How i try to find bugs: Print the variables. add following line after mid=ind((start+end)/2) print("start",start," mid",mid," end",end," arr",arr[mid])
21st Apr 2019, 3:28 PM
pur80a
pur80a - avatar
0
The problem is the following line: mid = int(start+end)/2) If start+end == 15 Then 15/2 = 7.5 and int(7.5) == 7 But the number you are looking for is at arr[8] One possible way to solve the bug is: mid= math.ceil((start+end)/2) and change start = mid in the last line of the function But therefore you would need to have the following line at the beginning: import math it doesn't find the first element because of the ceil function though
21st Apr 2019, 4:02 PM
pur80a
pur80a - avatar