Program for Binary Search in Java

Program

import java.util.Scanner;
 
class BinarySearch
{
 public static void main(String ar[])
 {  int i,mid,first,last,x,n,flag=0;
 
   Scanner sc=new Scanner(System.in);
   System.out.println("nEnter number of elements:");
   n=sc.nextInt();
 
   int a[]=new int[n];
 
   System.out.println("nEnter elements of array:");
   for(i=0;i<n;++i)
    a[i]=sc.nextInt();
 
   System.out.println("nEnter element to search:");
   x=sc.nextInt();  
 
   first=0;
   last=n-1;
 
   while(first<=last)
   {
    mid=(first+last)/2;
 
    if(a[mid]>x)
     last=mid-1;
    else 
     if(a[mid]<x)
      first=mid+1;
     else
     {
      flag=1;
      System.out.println("nelement found");
      break;
     }
   }
 
 if(flag==0)
  System.out.println("nelement not found");
 }
}

Output

Program for Binary Search in Java

Leave a Comment

error: Alert: Content is protected!!