Programming Examples
Java program to search any element in sorted array using binary search
Write a Java Program to input any sorted array and search a specific element in array using Binary Search.
Solution:
import java.util.*;
class BinarySearch
{
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Array : ");
int n=sc.nextInt();
int num[]=new int[n];
System.out.println("Enter the "+n+" Elements of Array in Accending order");
for(int i=0;i<n;i++)
{
num[i]=sc.nextInt();
}
System.out.println("Enter any number for Search : ");
int ch=sc.nextInt();
int min=0,max=n-1,mid;
boolean found=false;
while(min<=max)
{
mid=(min+max)/2;
if(num[mid]==ch)
{
found=true;
System.out.println("Element Found At "+mid+" index");
break;
}
else if(ch<num[mid])
{
max=mid-1;
}
else
{
min=mid+1;
}
}
if(found==false)
{
System.out.println("Element Not Found in Array ");
}
}
}
Output
Enter the size of Array :
8
Enter the 8 Elements of Array in Accending order
2
3
4
4
5
6
7
8
Enter any number for Search :
5
Element Found At 4 index
Enter the size of Array :
5
Enter the 5 Elements of Array in Accending order
22
33
44
55
66
Enter any number for Search :
50
Element Not Found in Array