+1 vote
in Class 12 by kratos

Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.

1 Answer

+5 votes
by kratos
 
Best answer

def binary_search( SORTEDLIST, number):

low=0

high=len( SORTEDLIST)

found=False

while(low<high) and found==False:

mid=(int) (low+high/2)

if SORTEDLIST[mid]==number:

print “Number found at”,mid

found=True

break

elif SORTEDLIST[mid]<number:

low=mid+1

else:

high=mid-1

if low >= high:

print “Number not found”

maxrange = inputfEnter Count of numbers: ”)

numlist = []

for i in range(0, maxrange):

numlist.append(input(“?”))

numlist.sort()

print “Sorted list”,numlist

number = inputfEnter the number”)

binary_search(numlist,number)

...