I've been trying to write binary search recursively. When I do this using the list[:] syntax I don't get the intended results with several errors coming up or not getting the correct values.
def binary_search(arr, val):
left = 0
right = len(arr)-1
mid = (left + right)//2
#Go through the array
if (val == arr[mid]):
return mid
#Check right side of arr
if (val > arr[mid]):
return binary_search(arr[mid+1:], val)
#Check left side of arr
return binary_search(arr[:mid], val)
EDIT: Example inputs and outputs
arr1 =[]
for i in range(10):
arr1.append(i)
for i in range(10):
print(binary_search(arr1,i))
I expect to get something like '0,1,2,3,4,5,6,7,8,9' but get '0,1,0,0,4,None ,None,2,0,0'
whileloop that contains an unconditional return. You'll never loop more than once, that way. (posting this as a comment and not an answer because I don't have any specific recommendations about what you should be doing instead)bisect