Reputation: 3018
I am getting value as "None" in my program?Where have I gone wrong?
lis2 = [1, 3, 6, 2, 5, 4, 8, 12]
lis2 = sorted(lis2)
start = 0
end = len(lis2)
mid = (start+end)/2
def binary_search(i):
global mid,start,end
if i==lis2[mid]:
return "Found"
elif i<lis2[mid]:
end = mid-1
mid = (start+end)/2
elif i>lis2[mid]:
start = mid+1
mid = (start+end)/2
else:
return "Not Found"
binary_search(i)
print(binary_search(6))
Any help is appreciated.Thanks in advance!
Upvotes: 0
Views: 65
Reputation: 689
Three mistakes are present -
binary_search(i)
instead of return binary_search(i)
start > end
, if ti happens then element is not present.end
to len(lis2)
, this will give IndexError: list index out of range
if you are trying to search for an element which is not present in the list and is greater than the max element in the list ( say 23 ). So change end = len(lis2)
to end = len(lis2)-1
Correct Code -
lis2 = [1, 3, 6, 2, 5, 4, 8, 12]
lis2 = sorted(lis2)
start = 0
end = len(lis2)-1
mid = int((start+end)/2)
def binary_search(i):
global mid,start,end
if(start>end):
return "Not Found"
if i==lis2[mid]:
return "Found"
elif i<lis2[mid]:
end = mid-1
mid = int((start+end)/2)
elif i>lis2[mid]:
start = mid+1
mid = int((start+end)/2)
return binary_search(i)
print(binary_search(6))
Upvotes: 1
Reputation: 1469
at the end of your function, you need to return the result when calling the function recursivley :
def binary_search(i):
global mid,start,end
if i==lis2[mid]:
return "Found"
elif i<lis2[mid]:
end = mid-1
mid = (start+end)/2
elif i>lis2[mid]:
start = mid+1
mid = (start+end)/2
else:
return "Not Found"
return binary_search(i) # <----- EDITED
Upvotes: 0