Write a java program for binary search?

devquora
devquora

Posted On: Jan 08, 2021

 

A JAVA program uses the Binary search algorithm to search an element in the given list of elements is as follows:

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 the 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 the number of elements:
7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Capgemini Java Interview Questions

    What is database normalization? Explain types of it.

    In SQL, normalization of data is a process through with data is organized in tables used for the reduction of redundancy and dependency of data. It divides large tables into smaller ones using some se...

    Capgemini Java Interview Questions

    What is difference between Class and object In JAVA?

    Difference between Class and object In JAVA:Class - A class is like a blueprint. It is the class with the help of which objects are created. The class holds together data and methods in one single...