Binary search in Java.


import java.util.Scanner;
public class BinarySearch
{
public static void main(String[] args)
{
int n,i,x,first,last,mid,flag=0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array size:");
n=sc.nextInt();
int a[] = new int[n];
System.out.println("Enter "+n+" elements of Array in Ascending \norder only:");
for(i=0;i<n;i++)
{
  a[i]=sc.nextInt();
}
System.out.print("Enter number you want to search:");
x=sc.nextInt();
System.out.println("You Entered number is:"+x);
sc.close();
first=0;
last=n-1;
mid=(first+last)/2;
while(first<=last)
{
  if(x==a[mid])
  {
    flag=1;
    break;
  }
  else if(x>a[mid])
   {
    first=mid+1;
   }
   else
   {
     last=mid-1;
   }
   mid=(first+last)/2;
}
   if(flag==1)
   {
     System.out.print("Entered number is found at:"+(mid+1)+" position.");
   }
   else
   {
     System.out.print("Enterd number is not found");
   }
}
}

*** Input && Output ***



Post a Comment

0 Comments