Saturday, May 16, 2015

Binary search program in java


Operations of the java program given below
The java program given below is a binary search program. When you will run the program, then you will be asked to provide the limit. The 5th line is to show the message.

In the 8th line a scanner object input has been created, otherwise we couldn't input anything using keyboard. And most importantly we have to import the packages as like as the first line.

By the 11th line an integer type data will be stored into a variable limit. We have to use limit to define how many data we will store into the array.

Using the 14th line we will again display a message to provide the items/data. 

import java.util.*;
public class bsa{
 public static void main(String args[]){
  //Message to input the limit
  System.out.print("Enter the limit: ");

  //Creating scanner object
  Scanner input = new Scanner(System.in);

  //Getting input into the variable limit
  int limit = input.nextInt();

  //Message to provide the items
  System.out.print("Enter the items: ");

  //Declaring int type array
  int data[] = new int[limit];

  //Storing data into an array
  for(int i=0; i<limit; i++){
   data[i] = input.nextInt();
  }

  //Message to provide the expected item
  System.out.print("Enter an item to search: ");

  //Storing expected item into variable
  int searchItem = input.nextInt();

  //Initializing beginning and end
  int beg = 1, end = limit;

  //Defining the mid
  int mid = (beg + end)/2;

  //While loop to find out the data
  while(beg <= end && data[mid] != searchItem){
   if(searchItem < data[mid]){
    end = mid - 1;
   } else {
    beg = mid + 1;
   }

   mid = (beg + end)/2;
  }

  //Increasing the array position by 1
  int arrayPos = mid + 1;

  //If statement to display message if data found or not
  if(data[mid] == searchItem){
   System.out.println("Data found at position: "+arrayPos);
  } else {
   System.out.println("Data not found!!!");
  }
 }
}

Advertisement

No comments:

Post a Comment