BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java program to perform binary search – Example

Last Updated: September 10, 2022 by Chaitanya Singh | Filed Under: Java Examples

Example Program to perform binary search on a list of integer numbers

This program uses binary search algorithm to search an element in given list of elements.

/* Program: Binary Search Example
 * Written by: Chaitanya from beginnersbook.com
 * Input: Number of elements, element's values, value to be searched
 * Output:Position of the number input by user among other numbers*/
import java.util.Scanner;
class BinarySearchExample
{
   public static void main(String args[])
   {
      int counter, num, item, array[], first, last, middle;
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 

      //Creating array to store the all the numbers
      array = new int[num];

      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
          array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();
      first = 0;
      last = num - 1;
      middle = (first + last)/2;

      while( first <= last )
      {
         if ( array[middle] < item )
           first = middle + 1;
         else if ( array[middle] == item )
         {
           System.out.println(item + " found at location " + (middle + 1) + ".");
           break;
         }
         else
         {
             last = middle - 1;
         }
         middle = (first + last)/2;
      }
      if ( first > last )
          System.out.println(item + " is not found.\n");
   }
}

Output 1:

Enter number of elements:
7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

Output 2:

Enter number of elements:
5
Enter 5 integers
12
3
77
890
23
Enter the search value:
99
99 is not found.

Top Related Articles:

  1. Java Program to Calculate average using Array
  2. Java program to print Floyd’s triangle – Example
  3. Java Program to Add Two Complex Numbers
  4. Java program to convert decimal to binary
  5. Sphenic Number in Java – Check and Print all numbers in a range

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Ashrumochan Senapati says

    May 14, 2014 at 4:07 AM

    Why you are still using the old approach for binary search.
    Directly we can use the utility methods of utility class – java.util.Arrays

    Methods Example-
    ===============
    public static int binarySearch(primitive() p,Primitive key)

    public static int binarySearch(Object() o,Object key)

    public static int binarySearch(Object() o,Object key,Comparator c)

    Reply
    • Srinivas Reddy says

      July 17, 2014 at 12:02 PM

      Thanks Ashrumochan for your suggestion. It works fine and great share……

      Reply
    • Deepak Raj says

      July 17, 2014 at 12:03 PM

      Nice one.. Thanks.

      Reply
  2. Lueos Joshef says

    November 11, 2014 at 8:03 AM

    Thanks Ashrumochan Senapati,Good to know about “java.util.Arrays” class. Really helped a lot…
    You made my day!!!

    Reply
  3. maulik says

    April 14, 2015 at 1:09 PM

    i found array index out of bound exception while executing this code.give me solution for that.

    Reply
  4. krishna says

    August 31, 2015 at 5:55 AM

    I just requesting a clarification , In my binary search algorithm classes it has been told that , if sort is not done before a Binary search it is almost equal to Linear search . In this example sorting of array is not done(Please correct me if I am missing something ) .

    Reply
    • Jagriti says

      September 7, 2015 at 4:26 PM

      Yes, as far as i know me too think sorting is required. This program gives false output if u search for the value 8 considering the above numbers

      Reply
  5. RAM says

    October 16, 2015 at 1:55 AM

    Yes..Sorting is prerequisite for Binary Search.

    Reply
  6. kishor singh says

    January 7, 2016 at 5:56 PM

    Enter number of elements:
    6
    Enter 6 integers
    12
    3
    5
    7
    9
    4
    Enter the search value:
    4
    4 is not found.

    Reply
  7. Javed says

    April 22, 2016 at 6:02 AM

    This is not binary search.. The basic requirement of binary search should be a presorted array in ascending order if iam not wrong…

    Reply
  8. Preeti says

    May 9, 2017 at 6:18 PM

    Yes , we should sort before searching the element.
    Arrays.sort(array)
    Otherwise above program wont work

    Reply

Leave a Reply Cancel reply

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

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap