Binary Search in Python (CBSE | CS | XI & XII)



#Binary Search
a=[5,7,11,13,16,19,23,27,30,34,38,40,41,42,45]
n=len(a)
beg=0
last=n-1
print(a)
srch=int(input('Enter the number to search: '))
flag=0
while beg<=last:
     mid=(beg+last)//2
     if srch==a[mid]:
          print('Number found at index no.',mid)
          flag+=1
          break;
     elif srch>a[mid]:
          beg=mid+1
     elif srch<a[mid]:
          last=mid-1

if flag==0:
     print('Number not found....')


Click to Watch Video Explanation

No comments

Post your comments

Powered by Blogger.