Compare these two implementations of binarySearch. The first is yours, the second is mine.
In your version, you are passing "slices", ie, entire copies of subarrays, to the recursive call. In my version, all recursive calls access the same array without copying it, and instead only low and high are passed as parameters.
# using slices, ie, copies of subarrays
def binarySearching(sortedArr,v):
# print(sortedArr)
if len(sortedArr)>=1:
mid = len(sortedArr)//2
if v<sortedArr[mid]:
return binarySearching(sortedArr[:mid],v)
elif v>sortedArr[mid]:
return binarySearching(sortedArr[mid+1:],v)
else:
return mid
else:
return None
# using low and high indices
def otherBinarySearching(sortedArr, v):
def auxiliary(low, high, v):
#print(low, high, sortedArr[low:high])
if high > low:
mid = (high + low) // 2
if v < sortedArr[mid]:
return auxiliary(low, mid, v)
elif v > sortedArr[mid]:
return auxiliary(mid+1, high, v)
else:
return mid
elif high == low:
return (low if v == sortedArr[low] else None)
return auxiliary(0, len(sortedArr), v)
# add some tests to make sure implementations are correct
if __name__=='__main__':
a = [x for x in range(0, 101, 2)]
b = [x for x in range(1, 100, 2)]
print('a: ', a)
print('b: ', b)
print('binarySearching: ', all(isinstance(binarySearching(a, x), int) for x in a) and all(binarySearching(a, x) is None for x in b))
print('otherBinarySearching: ', all(otherBinarySearching(a, x) == x / 2 for x in a) and all(otherBinarySearching(a, x) is None for x in b))
In addition, your version returns the wrong indices: the line return mid returns the index of v in the subarray binarySearching is currently looking at, instead of the index in the original array.
a = [x for x in range(0, 101, 2)] b = [x for x in range(1, 100, 2)] print(all(binarySearching(a, x) for x in a)) print(any(binarySearching(a, x) for x in b))should print "true" then "false" if your program is correct.a = [x for x in range(0, 101, 2)] b = [x for x in range(1, 100, 2)] print(all(binarySearching(a, x) == x / 2 for x in a) and all(binarySearching(a, x) is None for x in b))should print "true" if your program is correct.return midreturns the value ofmidwhich is the position ofvin the subarray you are currently searching, and not the position ofvin the original array.intwhenvis in the array andNonewhen it isn't withisinstance:a = [x for x in range(0, 101, 2)] b = [x for x in range(1, 100, 2)] print(all(isinstance(binarySearching(a, x), int) for x in a) and all(binarySearching(a, x) is None for x in b))