Binary Search In Java(Program)

import java.io.*;
class BinarySearch
{
public static void main(String args[])
{
try
{
int arr[]=new int[100];
int i,n,beg,mid,item,end;
DataInputStream dis=new DataInputStream(System.in);
System.out.println(“Enter The Number of elements:”);
n=Integer.parseInt(dis.readLine());
System.out.println(“Enter The Element In Sorted Order:”);
for(i=0;i<=n;i++)
{
arr[i]=Integer.parseInt(dis.readLine());
}
System.out.println(“Entered Elements Are:”);
for(i=0;i<=n;i++)
{
System.out.println(arr[i]);
}

System.out.println(“Enter The Element To Be Search:”);
item=Integer.parseInt(dis.readLine());
beg=1;
end=n;
mid=(beg+end)/2;
while(beg<=end && arr[mid]!=item) // Compare Item and Value of Mid
{
if(arr[mid]<item)
beg=mid+1;
else
end=mid-1;

mid=(beg+end)/2;
}

if(arr[mid]==item)
{
System.out.println(“Element Is Found At Location:”+mid);
}
else
{
System.out.println(“Element Is Not Found!!!!”);
}
}
catch(Exception e) {}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s