Proxy > Gmail Facebook Yahoo!

Java program to perform binary search



Example:
Consider an sorted array containing 5,15,25,30,35,40
Sorted array for binary search
Suppose we want to search for the number 30 in the given array. The algorithm performs the search in the following steps.
Step 1:
Compare the number to be searched with the middle element i.e 20 in this case. So the algorithm compares the number 30 with 20.

Step 2:
If the number to be searched is greater than the middle number, search operation is performed on the second part of the array. Else, on the first part of the array.

The procedure continues till array[mid] is the number requested by the user.
Program:
import javax.swing.*;
public class BinarySearch {
 public static void main(String[] args) {
  int array[] = new int[11];
  array[0] = 10;
  array[1] = 20;
  array[2] = 30;
  array[3] = 40;
  array[4] = 50;
  array[5] = 60;
  array[6] = 70;
  array[7] = 80;
  array[8] = 90;
  array[9] = 100;
  array[10] = 110;
  int size = array.length;
  int low = 0;
  int mid = low+size/2;
  int num=0;
  System.out.println("The current array contains following data: ");
  for(int i = 0 ; i<=10 ; i++)
  {
   System.out.print(array[i]+"\t");
  }
  System.out.println();
  String input_box = JOptionPane.showInputDialog("Enter the element to be searched: ");
  try //Putting the main code in the try block.
  {
  num = Integer.parseInt(input_box);
  if(num>array[size-1] || num < array[0]) //Main if
  {
   System.out.println("Number doesn't exist.");
  }
  else{
  while(array[(low+size)/2]!= num){
   if(num>array[(low+size)/2])
   {
    System.out.println("Setting low to "+mid);
    low = mid;
    mid=(mid+size)/2;
   }//End if
   else{

    System.out.println("Setting size to "+mid);
    size = mid;
    mid=mid/2;
    }  
  }//Close while loop
  System.out.println("The number is at position: "+(low+size)/2);
  }//End main if
  }//End try
  catch(Exception e)//Catching exception
  {
   JOptionPane.showMessageDialog(null, "Error:\nYou need to enter a number,not string", "Invalid Number!", JOptionPane.WARNING_MESSAGE);
  }
 }
}


Responses

0 Respones to "Java program to perform binary search"


Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar