It is a technique to search an element in the given list. In this technique, the complete list is divided into two halves. It means the element may be either present in the first half or second half.
Note: Binary search can be used only when the list elements are sorted in an order (either ascending or descending order).
l=eval(input("Enter a set of sorted numbers:"))
print("Elements of the list:",l)
num=eval(input("Enter the element to be searched:"))
flag=False
p=len(l)
first=0
last=p-1
while(first<=last):
mid=int((first+last)/2)
if l[mid]==num:
flag=True
break
if num<l[mid]:
last=mid-1
if num>l[mid]:
first=mid+1
if flag==True:
print("Element present.Search is successful!.")
else:
print("Element not present. Search is unsuccessful!.")
Contents
Output 1:
Enter a set of sorted numbers:[13,14,15,16,17,18,23,25,26]
Elements of the list: [13, 14, 15, 16, 17, 18, 23, 25, 26]
Enter the element to be searched:17
Element present.Search is successful!.
Output 2:
Enter a set of sorted numbers:[13,14,15,16,17,18,23,25,26]
Elements of the list: [13, 14, 15, 16, 17, 18, 23, 25, 26]
Enter the element to be searched:67
Element not present. Search is unsuccessful!.