I wanted to do binary search on a list but the result shows 'false' even if I check a number from the list.
def clist(a):
l = [2,6,5,9,7,1,4,8,3]
newl = sorted(l)
check = int(1+len(newl)/2)
if newl[check] == a:
return True
if check > a:
for x in newl[:check]:
if x == a:
return True
return False
if check < a:
for x in newl[check::]:
if x == a:
return True
return False
print(clist(7))
You could write your script in such a way that:
needle
is gt than the middle, then call bsearch
on the remaining right side of the listbsearch
with the left sidedef bsearch(needle, haystack):
l = len(haystack)
half = int(l / 2)
element = haystack[half];
if element == needle:
return element
if needle <= element:
return bsearch(needle, haystack[0:half])
if needle > element:
return bsearch(needle, haystack[half:l])
print(bsearch(7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
in binary search: