Binary Search
Binary Search
*;
class BinarySearch
{
public static void main(String args[])
{
int i,n,item;
Scanner sc=new Scanner(System.in);
BinarySearch obj=new BinarySearch();
System.out.println("Enter the length of the array:");
n=sc.nextInt();
int a[]=new int[n];
for(i=0;i<n;i++)
{
System.out.println("Enter the Value in Sorted order:");
a[i]=sc.nextInt();
}
System.out.println("Enter the Item which you want to Search");
item=sc.nextInt();
obj.binarysearch(a,item); //Function call
}
void binarysearch(int x[], int c) // Function Deffination
{
int n=x.length,beg=0,end=x.length-1,mid,flag=0;
while(beg<=end)
{
mid=(beg+end)/2;
if(x[mid]==c)
{
flag=1;
System.out.println("Item found in index:"+mid);
break;
}
else if(x[mid]>c)
{
end=mid-1;
}
else
{
beg=mid+1;
}
}
if(flag==0)
{
System.out.println("Item not found");
}
}
}