1.

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.

Answer»

def BinarySearch (Arr,l,R,X):

if R >= l:

mid = l + (R-l)//2

if Arr[mid] == X:

return mid

elif Arr[mid] > X: 

return BinarySearch(Arr,l,mid-1,X)

else:

return BinarySearch(Arr,mid+1,r,X)

else: return -1

Arr = [ 2, 3, 4, 10, 40 ]

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")



Discussion

No Comment Found

Related InterviewSolutions