Java program to search an element in sorted array using Binary search

import java.util.*;
class scan
{
 public static void main(String arg[])
  {
 int x[]=new int[100];
 int y,mid,beg,end,i,v,j,n;
   Scanner kb=new Scanner(System.in);
   System.out.println("Enter Size of array:- ");
   y=kb.nextInt();
   System.out.println("Enter elements is array:- ");
   for(i=0;i<y;i++)
    {
	 x[i]=kb.nextInt();
	}
	
	for(i=0;i<y;i++)
	 {
	  for(j=i+1;j<y;j++)
	   {
	    if(x[i]>x[j])
		 {
		    v=x[j];
			x[j]=x[i];
			x[i]=v;
		 }
	   }
	 }
	
	System.out.println("Sorted array is:- ");
	for(i=0;i<y;i++)
	{	
System.out.println(x[i]);
   }																																																						
System.out.println("Enter element you want to search");
	n=kb.nextInt();
	beg=1;
	end=y;
	mid=(beg+end)/2;
	
	 while(beg<=end &&  x[mid]!=n)
	 {
		 if(x[mid]<n)
		 {
			 beg=mid+1;
		 }
		 else
		 {
			 end=mid-1;
		 }
		 
		 mid=(beg+end)/2;
	 }
	 
	 if(x[mid]==n)
	    {
			mid++;
		 System.out.println("Element is found at location:- "+mid);
	    }
	 else
	    {
		 System.out.println("Element is not found");
	    }
	 
	}
}

OUTPUT:-

search

Leave a Reply

Your email address will not be published. Required fields are marked *