You are here

Binary search in Java

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

Binary search Java program

import java.util.Scanner;

class BinarySearch
{
  public static void main(String args[])
  {
    int c, first, last, middle, n, search, array[];
 
    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of elements");
    n = in.nextInt();
    array = new int[n];
 
    System.out.println("Enter " + n + " integers");
 
 
    for (c = 0; c < n; c++)
      array[c] = in.nextInt();

    System.out.println("Enter value to find");
    search = in.nextInt();
 
    first  = 0;
    last   = n - 1;
    middle = (first + last)/2;
 
    while( first <= last )
    {
      if ( array[middle] < search )
        first = middle + 1;    
      else if ( array[middle] == search )
      {
        System.out.println(search + " found at location " + (middle + 1) + ".");
        break;
      }
      else
         last = middle - 1;
 
      middle = (first + last)/2;
   }
   if (first > last)
      System.out.println(search + " isn't present in the list.\n");
  }
}

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 the Arrays class, which we can use.

import java.util.Arrays;

class BS
{
  public static void main(String args[])
  {
    char characters[] = { 'a', 'b', 'c', 'd', 'e' };
 
    System.out.println(Arrays.binarySearch(characters, 'a'));
    System.out.println(Arrays.binarySearch(characters, 'p'));
  }
}

The 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.