codescracker


java

Java Program Binary Search



« Previous Program Next Program »


Binary Search

To perform binary search in Java Programming, you have to ask to the user to enter the array size, then ask to enter the array elements. Now again ask to the user enter an element that he he/she want to search that element to start searching that element using the binary search technique.

Java Programming Code for Binary Search

Following Java Program first ask to the user to enter "how many element he/she want to store in a array", then ask to enter the array element one by one". After storing the element in the array, following program again ask to the user to enter the element which he/she want to search in the array whether the entered element/number is present in the list or not. The searching technique used here is binary search which is fast technique :

/* Java Program Example - Binary Search */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int n, i, search, first, last, middle;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Total Number of Elements : ");
       n = scan.nextInt();
	   
       System.out.print("Enter " +n+ " Elements : ");
       for(i=0; i<n; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       System.out.print("Enter a Number to Search..");
       search = scan.nextInt();
	   
       first = 0;
       last = n-1;
       middle = (first+last)/2;
	   
       while(first <= last)
       {
           if(arr[middle] < search)
           {
               first = middle+1;
           }
           else if(arr[middle] == search)
           {
               System.out.print(search+ " Found at Location " +middle);
               break;
           }
           else
           {
               last = middle - 1;
           }
           middle = (first+last)/2;
       }
       if(first > last)
       {
           System.out.print("Not Found..!! " +search+ " is not Present in the List.");
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output. Above Java Programming Example Output (Element found):

java program binary search

Above Java Programming Example Output (Element Not found):

binary search program in java

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test