Anda di halaman 1dari 2

import java.io.

*;
class BINARYSEARCH
{
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 int binarysearch(int a[],int l,int h,int x)
{
if(l==h)
{
if(x==a[l])
return l;
else
return -1;
}
else
{
int mid=(l+h)/2;
if(x==a[mid])
return mid;
if(x<a[mid])
return binarysearch(a,l,mid-1,x);
else
return binarysearch(a,mid+1,h,x);
}
}
public static void main(String[] args)
{
try
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the number of the elements.");
int n=Integer.parseInt(in.readLine());
int a[]=new int[n];
System.out.println("Enter the elements of the array.");
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);
int f=binarysearch(a,0,n-1,x);
if(f==-1)
System.out.println("Element not found.");
else
System.out.println("Element found at "+(f+1)+" p
osition in sorted array.");
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}
Enter the number of the elements.
5
Enter the elements of the array.
34
76
81
03
45
Enter the element to be searched.
45
Element found at 3 position in sorted array.
Press any key to continue...

Anda mungkin juga menyukai