Friday, August 19, 2011

Binary Search Program Source Code in Java


The Java Program given below can be used to find an Element in array using Binary Search Technique.
The Main steps Involved here are
1)A Pivot Element is Found
2)The array is sorted in such a way that elements greater than the pivot lies to the right and elements lesser lies to the left of the pivot.
3)Linear search is applied by taking the appropriate limits.,depending upon whether the element to be searched is greater or lesser than the pivot. 
 class array  
 {  
  DataInputStream get;  
  int a[];  
  int i,j,n,key;  
  void getdata()  
  {  
  try  
  {  
   get=new DataInputStream(System.in);  
   System.out.println("Enter the limit");  
   n=Integer.parseInt(get.readLine());  
   a=new int[n];  
   System.out.println("Enter the elements");  
   for(i=0;i<n;i++)  
   a[i]=Integer.parseInt(get.readLine());  
  }  
  catch(Exception e)  
  {  
   System.out.println(e.getMessage());  
  }  
  }  
 void sorting()  
 {  
 int t,j;  
 for(j=0;j<n;j++)  
 {  
  for(i=0;i<n-1;i++)  
  {  
  if(a[i]>a[i+1])  
   {  
   t=a[i];  
   a[i]=a[i+1];  
   a[i+1]=t;  
   }  
  }  
  }  
  System.out.println("Elements in ascending order is:");  
  for(i=0;i<n;i++)  
  System.out.print(a[i]+" ");  
  System.out.println();  
  try  
  {  
  System.out.println("Enter the key element");  
  key=Integer.parseInt(get.readLine());  
  }  
  catch(Exception e)  
  {  
   System.out.println(e.getMessage());  
  }  
  }  
  void search()  
  {  
  int m,flag=0,l,u,p=0;  
  l=0;  
  u=n-1;  
  while(l<=u)  
  {  
   m=(l+u)/2;  
   if(a[m]==key)  
   {  
   flag=1;  
   p=m+1;  
   break;  
   }  
   else if(a[m]<key)  
   l=m+1;  
   else  
   u=m-1;  
  }  
  if(flag==0)  
   System.out.println("The number is not found");  
  else  
   System.out.println("The number is found in:"+p);  
  }  
 }   
 class binarysearch  
 {  
 public static void main(String arg[])  
 {  
  array obj=new array();  
  obj.getdata();  
  obj.sorting();  
  obj.search();  
  }  
 }  


4 comments:

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.