Binary Search program in Python- In this program, at first, we will input few element. After that program search for a given element using Binary search. If the list is finds a elements matched then it shows Element present. This python project is useful for beginners and CBSE KV School Class 11 and Class 12 students computer science practical file and NIELIT O Level module.
Objective– WAP to input a list of integers and search for a given number using binary search
Python code for the program
Explanation of python code->
def bsearch(L,n):#a function is being declaring taking values one for entering the list of number and the number to find n
start=0 #in this declaration we take a variable start=0
end=len(L)-1 #in the end
while start<=end: #Condition for while loop
mid=(start+end)//2 #the mid
if L[mid]==n: #now middle number between start and end is checked whether it is equal to the mid number
return True
elif L[mid]<=n: #if this condition is true then the below line works
start=mid+1
else: #else the below will be doing
end=mid-1
else:
return False
L=eval(input(“Enter the list of numbers”)) #the list is entering
n=int(input(“Enter the number to find”)) #the number to find
L.sort() #sorted the list and stored in L itself
if bsearch(L,n): # the above program is called with the sorted list and n number to be finding
print(“Element found”)
else:
print(“Element not found”)
Output of Binary Search program
Testing of Python Program
Case 1
Input of the program is 15,16,17,18,19.
Element to be Search 5
Element is not found in the list after sorting,
Therefore out put is – Element not found
Case 2
Input of the program is 5, 15, 16,17,18
Element to be Search 5
Element is found in the list after sorting,
Therefore out put is – Element found
Well done . Our Binary Search Program using Python language is working fine.
Click here to download source code -> click here
for more python program -> click here
Input a welcome message and display it in Python
Display the larger / smaller number in Python.
Greatest of Three Numbers in Python using Nested if
Patterns using nested loop in Python
Program to Print Pattern in Python
Program to input the value of x and n and sum of series in Python
Python Program for Armstrong, Prefect Number, Palindrome
Program of Prime number by recursion in python
Prime Number Program in Python
Write a Program to Print Fibonacci Series in Python
Python program to count number of vowels in a string
Whether a String is Palindrome or not in Python
Linear search in python using list
Program to read a text file in python
Python program to read a file line by line
Program to Count Vowels and Consonants in Python
Python Leap Year Program for Beginners
Python Program to Print Series and Addition
Binary Search Program in Python
Program to find sum of digits in python
Sum of numbers divisible by 3 and 5 in python