BINARY SEARCH - RECURSIVE FUNCTION IN PYTHON

Write a Recursive function in python BinarySearch(Arr,l,R,X) to search the given
element X to be searched from the List Arr having R elements where l represents
lower bound and R represents upper bound.

#Arr is for Array
#ln is for Length of array
#R is Length -1 of array for recrusion concept
#X is searching element

def BinarySearch(Arr,ln,R,X):
    if R >= ln:
        mid = ln + (R-ln)//2
        if Arr[mid] == X:
            return mid
        elif Arr[mid] > X:
            return BinarySearch(Arr,ln,mid-1,X)
        else:
            return BinarySearch(Arr,mid+1,R,X)
    else:
        return -1


#main
Arr = [2, 13, 24, 30, 36, 39, 40, 51, 75]
X =int(input('Enter element to be searched:'))
result = BinarySearch(Arr,0,len(Arr)-1,X)
if result != -1:
    print ("Element is present at index ", result)
else:
    print ("Element is not present in array")


Output:
Enter element to be searched:25
Element is not present in array

No comments

Post your comments

Powered by Blogger.