0
Please, solve this binary search algorithm problem
l=[1,2,4,6,8,10,12,14,24,57] def binary_search(data,num): l=0 u=len(data) while l<=u: mid = (l+u)//2 if data[mid] == num: return True elif num<data[mid]: mid=u else: mid=l return False print(binary_search(l,8))
3 Answers
+ 4
Shourov Saha ,welcome last answer was wrong , lol. I deleted it.
here is correct one:
[consider data in ascending order]
Binary search is applied only to sorted data. It's similar to finding desired page in a book. You start from middle page and if it's desired page means you found what you needed so say 'True'.page number exists.
If the opened page has number greater than required one where you'll search? obviously in left portion where all numbers are less than one that we found.
So to search only in left part we make last index = mid-1 and follow same process of searching for this small part.
Else if the page that you found is less than what you wanted, where you'll search ?obviously in right portion. For this you set variable indicating lower bound is set to mid+1
What you need to correct in program :
1. replace len(data) by len(data)-1 because indexing start from 0
2.in elif num<data[mid] set u=mid-1
3.in else set l=mid+1
Search on net for better understanding.
+ 2
just to show why your code can't work:
while l <= u
mid = (l+u)//2
data[5] is 10
10 > 8 -> mid = l
doing the loop again -> mid = (l + u)//2
It should be clear that you have to change l or u to calc new mid otherwise the loops checks 10 > 8 again and again.
+ 1
Thanks š