You are on page 1of 2

import java.io.

DataInputStream;
import java.io.*;
public class BINARYSEARCHNR {
/**
* @param args
*/
static void bubblesort(int a[])
{
for(int i=a.length-2;i>=0;i--)
for(int j=0;j<=i;j++)
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
static void binarysearch(int a[],int x)
{
int l=0;
int r=a.length-1;
int mid=(l+r)/2;
while(l<=r&&a[mid]!=x)
{
if(x<a[mid])
r=mid-1;
else
l=mid+1;
mid=(l+r)/2;
}
if(l>r)
System.out.println("Element not found.");
else
System.out.println("Element found at "+(mid+1)+" in sort
ed array.");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DataInputStream in=new DataInputStream(System.in);
int n;
try
{
System.out.println("Enter the number of the elements.");
n=Integer.parseInt(in.readLine());
int a[]=new int[n];
System.out.println("Enter the elements.");
for(int i=0;i<n;i++)
a[i]=Integer.parseInt(in.readLine());
System.out.println("Enter the element to be searched.");
int x=Integer.parseInt(in.readLine());
bubblesort(a);
binarysearch(a,x);
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}http://downloads.ziddu.com/downloadfiles/704803/nS.etal.BarronsGRE.12th.ed.Barr
ons669s1997.pdf
Enter the number of the elements.
5
Enter the elements.
45
67
89
12
34
Enter the element to be searched.
67
Element found at 4 in sorted array.
Press any key to continue...

You might also like