Custom Search

Saturday 16 June 2012

Binary Search Using JAVA


import java.io.*;
public class binarysearch
{
public static void main(String ar[])throws IOException
{
int a[]=new int[10];
int n,i,j,t,elem,flag=0,beg=0,end,mid;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the limit: ");
n=Integer.parseInt(br.readLine());
System.out.println("enter the elements: ");
for(i=0;i
{
a[i]=Integer.parseInt(br.readLine());
}

for(i=0;i
{
for(j=1;j
{
if(a[j-1]>a[j])
{
t=a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
System.out.println("sorted array is: ");
for(i=0;i
{
System.out.print(a[i]);
System.out.print("\t");
}
System.out.println("\nenter the element to be searched: ");
elem=Integer.parseInt(br.readLine());
end=n;
while(beg<=end)
{
mid=(beg+end)/2;
if(a[mid]==elem)
{
flag=1;
System.out.println("element found in the position ");
System.out.println(mid+1);break;
}
if(a[mid]
beg=mid+1;
if(a[mid]>elem)
end=mid-1;
}
if(flag==0)
System.out.println("element not found");
}
}

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...