Binary Search Algorithm: a python recursive code
Binary search algorithm assumes that (a) the list/array is sorted either ascendingly or descendingly (b) All the elements in the list/array are present.
Get kafleZ’s stories in your inbox
Join Medium for free to get updates from this writer.
Binary search algorithm works on the principle of divide and attack. It goes to the midway of the list in recursive way such that it narrow down the location of target value (i.e. key ). To narrow down the location of target element, the algorithm evaluate if the element value at mid-way of the narrowed list is greater or smaller than the key and then create new low and high index value to find the new mid point in recursive manner which is also consistently checked if it equals to key value. The code itself may be more explanatory.
#Binary Search Algorithms
def binarySrc(arr, high, low, key):
mid = (high+low)//2
if mid >0 and mid!=low:
if arr[mid]==key: return mid
elif arr[high]==key: return high
elif arr[low]==key: return low
elif arr[mid]>key: return binarySrc(arr, mid, low, key)
elif arr[mid]<key: return binarySrc(arr, high, mid, key)
else:
return ('Check provided key and list') #in case of error in input or list
#Sample Execution
arr = [2, 2, 3, 4, 4,10, 10, 40, 50]
high = len(arr)-1
low = 0
#key = 0 #what if the input is out of the list and is smaller than the smallest value in the list
#key = 100 #what if the input is out of the list and is greater than the greatest value in the list
key = 40
print(binarySrc(arr, high, low, key))







