You are here

Java program for binary search

Java program for binary search: This code implements binary search algorithm. Please note that input numbers must be in ascending order. If they are not then you must sort them first.

Java programming code

  1. import java.util.Scanner;
  2.  
  3. class BinarySearch
  4. {
  5.   public static void main(String args[])
  6.   {
  7.     int c, first, last, middle, n, search, array[];
  8.  
  9.     Scanner in = new Scanner(System.in);
  10.     System.out.println("Enter number of elements");
  11.     n = in.nextInt();
  12.     array = new int[n];
  13.  
  14.     System.out.println("Enter " + n + " integers");
  15.  
  16.  
  17.     for (c = 0; c < n; c++)
  18.       array[c] = in.nextInt();
  19.  
  20.     System.out.println("Enter value to find");
  21.     search = in.nextInt();
  22.  
  23.     first  = 0;
  24.     last   = n - 1;
  25.     middle = (first + last)/2;
  26.  
  27.     while( first <= last )
  28.     {
  29.       if ( array[middle] < search )
  30.         first = middle + 1;    
  31.       else if ( array[middle] == search )
  32.       {
  33.         System.out.println(search + " found at location " + (middle + 1) + ".");
  34.         break;
  35.       }
  36.       else
  37.          last = middle - 1;
  38.  
  39.       middle = (first + last)/2;
  40.    }
  41.    if (first > last)
  42.       System.out.println(search + " isn't present in the list.\n");
  43.   }
  44. }

Output of program:
Binary Search Java program

Download Binary Search Java program class file.

Other methods of searching are Linear search and Hashing. There is a binarySearch method in Arrays class which can also be used.

  1. import java.util.Arrays;
  2.  
  3. class BS
  4. {
  5.   public static void main(String args[])
  6.   {
  7.     char characters[] = { 'a', 'b', 'c', 'd', 'e' };
  8.  
  9.     System.out.println(Arrays.binarySearch(characters, 'a'));
  10.     System.out.println(Arrays.binarySearch(characters, 'p'));
  11.   }
  12. }

binarySearch method returns the location if a match occurs otherwise -(x+1) where x is the number of elements in the array. For example, in the second case above when p isn't present in characters array the returned value will be -6.