Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

BINARY SEARCH

SOURCE CODE:
def binarysearch(List, elem):

beg = 0

last=len(List)-1

while(beg<=last):

mid=(beg+last)/2

if(elem==List[mid]):

return mid

elif(elem>List[mid]):

beg=mid+1

else:

last=mid-1

return -1

n=input('enter lenghth of list:')

List=[0]*n

for j in range(n):

List[j]=input('Enter element:')

elem=input('Enter element to be searched for:')

index=binarysearch(List, elem)

if index:
print'Element found at index', index, 'position =', index + 1

else:

print 'Element not found'

OUTPUT:

You might also like