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
#main program
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 ")
Output
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
============ RESTART: C:\Users\acer\Desktop\nsp\bimary search.py ============
enter element to be searched : 4
element is present at index 2
>>>
============ RESTART: C:\Users\acer\Desktop\nsp\bimary search.py ============
enter element to be searched : 40
element is present at index 4
>>>
=========== RESTART: C:/Users/acer/Desktop/nsp/bimary search-c.py ===========
enter element to be searched : 3
element is present at index 1
>>>
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
#main program
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 ")
Output
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
============ RESTART: C:\Users\acer\Desktop\nsp\bimary search.py ============
enter element to be searched : 4
element is present at index 2
>>>
============ RESTART: C:\Users\acer\Desktop\nsp\bimary search.py ============
enter element to be searched : 40
element is present at index 4
>>>
=========== RESTART: C:/Users/acer/Desktop/nsp/bimary search-c.py ===========
enter element to be searched : 3
element is present at index 1
>>>
No comments:
Post a Comment