Header Ads Widget

Write a python program for the binary search.

 what is binary search-

In binary search we compare the value with the mid value .   

Let's we have to search x for this in binary search we use following steps:-

  1. compare x with the mid value.
  2. if mid value is equal to number then return .
  3. if value is greater than mid value then change lower limit by mid+1 .
  4. if value is less than mid value then change upper limit by mid-1.

Code:-


list=[]
n=int(input("Enter the number of element in the list "))
for i in range(n):
list.append(int(input()))
value=int(input("Enter the value to be searched "))

# logic for binary search

lb=0
ub=n
while(lb<=ub):
mid=(lb+ub)//2
if list[mid]==value:
print("Value is present in list ")
break
elif list[mid]>value:
ub=mid-1
elif list[mid]<value:
lb=mid+1

Output:-


Enter the number of element in the list 6
12
23
45
67
87
89
Enter the value to be searched 45
Value is present in list

Recommended Post:-

         MCQs:-