Question
Write a program to perform binary search on a list of integers given below, to search for an element input by the user. If it is found display the element along with its position, otherwise display the message “Search element not found”.
5,7,9,11,15,20,30,45,89,97
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class BinarySearch
{
public static void main(String[]args)
{
int size=0,lower=0,upper=0,M=0;
boolean flag=false;
Scanner sc=new Scanner(System.in);
int arr[]={5,7,9,11,15,20,30,45,89,97};
size=arr.length;
System.out.println("Elements given array:");
for(int i=0;iarr[M])
{
lower=M+1;
}
else
{
upper=M-1;
}
}
if(flag==false)
{
System.out.println("Search element not found");
}
}
}
Python
li=[5,7,9,11,15,20,30,45,89,97]
print("Elements in given list:")
print(li)
lower=0
upper=len(li)-1
mid=0
flag=False
elementToBeSearched=int(input("Enter Element to be searched:"))
while(lower<=upper):
mid=(lower+upper)//2
if(li[mid]==elementToBeSearched):
print("Element is available at index:",(mid+1))
flag = True
break
elif(li[mid]< elementToBeSearched):
lower=mid+1
else:
upper=mid-1
if(flag==False):
print(elementToBeSearched,"not found in given List")