Skip to main content

Program in Java Binary Search Numbers

Program in Java to implement binary search on numbers


import java.util.Scanner;
class BinarySearch
{
 public static void main(String args[])
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the number of elements: ");
  int n = sc.nextInt();
  int A[] = new int[n]; //array initialized
  System.out.println("Enter the values into the array in ascending or descending: ");
  for(int i=0;i<n;i++)
  {
   A[i]=sc.nextInt(); //accepting the values into the array
  }
  System.out.println("Enter the value you want to find: ");
  int v = sc.nextInt();
  int start=0,end=A.length-1; // to store the starting and ending index of the array
  int pos=-1; //to store the index of the element from the array
  int flag=0; //to store the presence of the element of the array
  while(start<=end)
  {
   int mid = (start+end)/2;
   if(A[mid]>v)
    end=mid-1;
   else if(A[mid]<v)
    start=mid+1;
   else{ //when A[mid]==v
    pos=mid; //store the index
    flag=1; //set flag to 1
    break; //stop the loop
    }
  }
  if(flag==1)
   System.out.println(v+" is present at index "+pos);
  else
   System.out.println("Element not found");
    
 }
}

Popular posts from this blog