Reputation:
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))
Upvotes: 1
Views: 140
Reputation: 124
Please go through this:
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 newl[check] > a: #fixed the bug here
for x in newl[:check]:
if x == a:
return True
if newl[check] < a: #fixed the bug here
for x in newl[check:]:
if x == a:
return True
return False #Return false should be universal. When the entire search fails it should be called.
print(clist(7))
Upvotes: 1
Reputation: 4189
Your function is not binary search, you are checking element by element of a sorted list after checking the middle element.
def binary_search(arr, i):
n = len(arr)
arr = sorted(arr)
left = 0
right = n - 1
# Define the condition when the loop should be broken
while (left <= right):
mid = left + (right-left) // 2
if arr[mid] == i:
return True
elif arr[mid] < i:
left = mid + 1
else:
right = mid - 1
return False
l = [2,6,5,9,7,1,4,8,3]
i = 7
binary_search(l, i)
Upvotes: 0
Reputation: 14179
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:
Upvotes: 2