Implementing Binary Search in Java

A binary search algorithm finds the position of a specified input value (the search “key”) within an array sorted by key value.

import java.io.DataInputStream; 
          
class BinarySearch
{
	public static void main(String args[ ])
	{
		int i,n = 0,KEY, flag=0;
		String ans="y";
 		int x[] = new int[25];
		DataInputStream in = new DataInputStream(System.in); 

                try
		{
		    System.out.print("Enter how many numbers to be stored : ");
               	    n = Integer.parseInt(in.readLine());
		    System.out.println("Enter the number in INCREASING ORDER PLEASE.");
                    System.out.println("Enter "+n+" numbers ....");
                    for(i=1;i<=n;i++)
                    {
                 	System.out.print("\t\tElement ["+i+"]=");
            	        x[i] = Integer.parseInt(in.readLine());
                    }
		    do
  		    {
		    	System.out.print("Enter the number to be searched  : ");
               	    	KEY = Integer.parseInt(in.readLine());

		    	flag = Binary_Search(x,n,KEY);
		    	if (flag == -1)
		   		System.out.println(" Number Not present in the given array");
		    	else
				System.out.println(" Number "+KEY+" found at "+flag+" location in the array");


			System.out.print(" Want to search another number ?");
			ans=in.readLine();
		     }while((ans.equals("y"))||(ans.equals("Y")));

		}
		catch(Exception e) {  System.out.println("I/O Error");   }
	}
    	static int Binary_Search(int K[ ],int n,int KEY)			
	{
  		 int low=1;
  		 int high=n;
  		 int mid;
   		 mid=(low+high)/2;  
  		 while (high>=low)
		 {
			if (K[mid]==KEY)
			   return(mid);
    			else
     			{
		            if(KEY>K[mid])
				low=mid+1;  			 
			    else
	  		        high=mid-1;  
			    mid=(low+high)/2;
    			}
   		 }
                 return(-1);
	}

}

/*******************************************
                   OUTPUT
	
Enter how many numbers to be stored : 5
Enter the number in INCREASING ORDER PLEASE.
Enter 5 numbers ....
Element [1]=10
Element [2]=20
Element [3]=30
Element [4]=40
Element [5]=45
Enter the number to be searched  : 40
Number 40 found at 4 location in the array
Want to search another number ?Y
Enter the number to be searched  : 10
Number 10 found at 1 location in the array
Want to search another number ?Y
Enter the number to be searched  : 25
Number Not present in the given array
Want to search another number ?N
Process Exit...

**************************************************/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.